简体   繁体   中英

Angular 2 routing in ES5?

The Angular 2 ES5 cheat sheet says to do this:

var MyComponent = ng.router.RouteConfig([
  { path: '/:myParam', component: MyComponent, as: 'MyCmp' },
  { path: '/staticPath', component: ..., as: ...},
  { path: '/*wildCardParam', component: ..., as: ...}
]).Class({
  constructor: function() {}
});

However, I can't figure out how to specify the @Component stuff on that class so that I can actually instantiate it. For example,

ng.router.RouteConfig([...]).Component({})

throws an exception because the result of .RouteConfig doesn't have a .Component method. Similarly, the result of .Component doesn't have a .RouteConfig method. How do you get this set up?

I've done the following way which seems to work well.

app.AppComponent = ng.core
    .Component({
       selector: 'the-app',
       template: `
          <h1>App!!!</h1>
          <a [routerLink]="['Children']">Children</a>
          <a [routerLink]="['Lists']">Lists</a>
          <router-outlet></router-outlet>
       `,
       directives:[
          app.ListsComponent,
          app.ChildrenComponent,
          ng.router.ROUTER_DIRECTIVES
       ]
    })
    .Class({
       constructor: [ng.router.Route, function(_router) {
           this._router = _router; // use for navigation, etc
       }]
    });
app.AppComponent = ng.router
    .RouteConfig([
       { path: '/', component:app.ListsComponent, name:'Lists' },
       { path: '/children', component:app.ChildrenComponent, name:'Children' }
    ])(app.AppComponent);

Since both ng.core.Component and ng.router.RouteConfig are decorators you can write:

app.AppComponent = ng.core.Class(...);
app.AppComponent = ng.core.Component(...)(app.AppComponent);
app.AppComponent = ng.router.RouteConfig(...)(app.AppComponent);

Hope that helps.

Here's a possible way I managed to finally get working. I'm open to others posting better solutions:

app.AppComponent = ng.core
    .Class({
        constructor: [
            function() {
            }
        ]
    });

app.AppComponent.annotations = [
    ng.router.RouteConfig([
        { path: '/', component:app.ListsComponent, name:'Lists' },
        { path: '/children', component:app.ChildrenComponent, name:'Children' }
    ]).annotations[0],

    new ng.core.ComponentMetadata({
      selector: 'the-app',
      template: '<h1>App!!!</h1>' +
        '<a [routerLink]="[\'Children\']">Children</a>' +
        '<a [routerLink]="[\'Lists\']">Lists</a>' +
        '<router-outlet></router-outlet>',
      directives:[
          app.ListsComponent,
          app.ChildrenComponent,
          ng.router.ROUTER_DIRECTIVES
      ]
  })
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM