Angular 2 - how to use the new angular 2.0.0-rc.1 router

后端 未结 6 1947
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 13:11

I\'ve started to write a new angular 2 project and I found that I installed 2 angular router:

  1. \"@angular/router\": \"2.0.0-rc.1\",
6条回答
  •  抹茶落季
    2020-12-13 13:33

    Here is how to use the Angular 2 Router (RC1), compared to the beta (deprecated) one:

    • Routes replaces RouteConfig.
    • Inside your config there is a new syntax:

      {path: '/path', component: MyPathComponent}

      instead of:

      {path:'/path', name: 'MyPath', component: MyPathComponent}

    • Using routerLink is now like that:

      Click to navigate

      Instead of:

    Shark Crisis

    • Also there is no RouteParams anymore, instead you get the params using the router lifecycle hooks: CanActivate, OnActivate, and CanDeactivate.

    If you used params inside ngOnInit, you can do that like this now:

    routerOnActivate(curr: RouteSegment): void {
               curr.getParam('id');
           }
    

    You will end up having something like this:

    import {ROUTER_DIRECTIVES, Router, Routes} from "@angular/router";
    
    @Injectable()
    @Component({
        selector: "my-app",
        templateUrl: `Click to go to component 1`,
        directives: [ROUTER_DIRECTIVES]
    })
    @Routes([
        {path: "/component1", component: Component1},
        {path: "/component2", component: Component2}
    ])
    export class AppComponent {
        constructor(private _router: Router) {
            //If you want to use Router in your component (for navigation etc), you can inject it like this
        }
    }
    

    Update (9/6/16): It seems that Angular 2 RC1 Router is being deprecated like the old one. The new recommendation is to use version 3.0.0-alpha.3 of @angular/router.

    Here is more info at the Angular blog: http://angularjs.blogspot.co.il/2016/06/improvements-coming-for-routing-in.html

    Here is an overview of the new router: http://victorsavkin.com/post/145672529346/angular-router

    And here is a working plunker: http://plnkr.co/edit/ER0tf8fpGHZiuVWB7Q07?p=preview

提交回复
热议问题