AndyGrom
AndyGrom

Reputation: 601

How do I configure the Angular2 router that component name was of type string?

It is necessary that to configure the router from an external json-file

Example which contains a compilation error:

@RouteConfig([{
    path: '/dashboard', name: 'Dashboard', component: 'Dashboard'
}])

Note at component: 'Dashboard' - it is wrong. The component field must be of Type type. Anothe way is use Router.config() method, but I don't know how to use it. I tried, but I could not. Is it possible in the Anular2 router? In the angular1 I can specify controller name as a string value.

Upvotes: 2

Views: 1036

Answers (2)

AndyGrom
AndyGrom

Reputation: 601

I solved the problem by using a simple typescript decorator.

/***
 * Routing components storage
 * @type {Map<string, Function>}
*/
export var routingComponents = new Map<string, Function>();

/***
 * Decorator function
 * @returns {function(any): *}
 * @constructor
*/
export function RoutingComponent(name?: string) {
    return function (target:any) {
        routingComponents.set(name || target.name, target);
        return target;
    }
}

How to use the decorator

@Component({ selector: '', template: '' })
@RoutingComponent()
export class Dashboard {
    constructor(){}
}

Next, we can create RouteDefinition instance

private makeRoute(metadataItem: any): RouteDefinition {
    let component = routingComponents.get(metadataItem.name);
    if (!component) {
        component = CleanComponent;
    }

    var route: RouteDefinition = {
        name: metadataItem.name,
        path: metadataItem.url,
        useAsDefault: metadataItem.default,
        component: component
    };

    return route;
}

Upvotes: 1

user3636086
user3636086

Reputation: 823

If you want to use Router.config(), you can follow these steps:

1) In your main component, define your routes in a variable:

  private myMainRoutes: RouteDefinition[] = [
    { path:      '',
      component: HomeCmp,
      name:      'HomeCmp'
    },
    { path:      'dashboard',
      component: DashboardCmp,
      name:      'DashboardCmp'
    },
    { path:      'error',
      component: ErrorCmp,
      name:      'ErrorCmp'
    },
    { path:      '**',
      redirectTo: ['ErrorCmp']
    }
  ];

2) Use that variable in the main component constructor, using Router dep. injection.

class MainCmp  {
  private myMainRoutes: RouteDefinition[] =  ... ; // from above

  constructor(private router_: Router) {
    router_.config(this.myMainRoutes);
  }
}

Hope it helps!

Upvotes: 0

Related Questions