Skip to content

[Feature] Future States #2739

Closed
Closed
@amcdnl

Description

@amcdnl

1.0 no longer supports future states.

On the flip side, it is easier to swing this in 1.0 without an advanced plugin. I wanted to start the discussion for what my implementation looks like.

This implementation relies on: ng1, oclazyload, systemjs, ui-router 1.0apha4.

const services = [ '$q', '$state', 'cfpLoadingBar',
  'ng2.Compiler', 'ng2.ComponentFactoryRefMap', '$transitions' ];

export const configLaziness = [
  ...services,
  ($q, $state, $ocLazyLoad, compiler, componentFactoryRefMap, $transitions) => {

    function buildState(src) {
      let def = $q.defer();

      System.import(src).then(function(loaded){
        let newModule = loaded;
        if(!loaded.name){
          newModule = loaded.default;
        }

        adapter.compileNg2Components(compiler, componentFactoryRefMap);

        $ocLazyLoad.load(newModule).then(function(){
          cfpLoadingBar.complete();
          def.resolve();
        }, function(err) {
          throw err;
        });
      });

      return def.promise;
    };

    $state.$urlRouter.urlRouterProvider.otherwise(($injector, $location) => {

     /// below few lines sucks and is a bit nieve
      const url = $location.url().replace(/^\/?|\/?$/, ''); 
      const splits = url.split('/');
      const state = routes.find(r => {
        return r.urlPrefix.indexOf(splits[0]) > -1; 
      });

      if(state) {
        buildState(state.src).then(() => {
          $state.$urlRouter.sync();
        });
      } else {
        $state.go('404');
      }
    });

    $state.stateProvider.onInvalid(($to$, $from$, $state) => {
      const name = $to$.name();
      let state = routes.find(r => { return r.stateName === name });

      if(state) {
        var redirect = {
          to: $to$.identifier(),
          toParams: $to$.params(),
          options: $to$.options()
        };

        buildState(state.src).then(() => {
          $state.go(redirect.to, redirect.toParams, redirect.options);
        });
      } else {
        $state.go('404');
      }
    });
  }
];

and the route definitions look like:

[
  {
    "stateName": "apps",
    "urlPrefix": "/apps",
    "src": "app/admin/apps/apps.js"
  }
]

and this is configured like:

import angular from 'angular';
import { configRouting, configLaziness } from 'routing.js';

let app = angular.module('app', [ 'ui.router' ]);
app.config(configRouting);
app.run(configLaziness);

Its also worth noting this supports angular2 lazy loading.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions