@angular/router 3.0.0-alpha.3: How to migrate OnAc

2020-08-17 17:25发布

问题:

I just upgraded @angular/router to 3.0.0-alpha.3. However, I cannot find the interface OnActivate which was available in 2.0.0-rc.1. Any hint is appreciated.

回答1:

I'm personally not convinced that CanActivate and Deactivate guards are the best places to migrate OnActivation logic that isn't a guard of some sort.

Maybe the new router events are a better option: How to use NavigationStart



回答2:

Since we have no documentation yet and is coming in the following weeks. You wanted a hint. Here is what I found for you. It looks like you have to pass an additional parameter and specify a class to handle the lifecycle hooks?

import { CrisisDetailComponent } from './crisis-detail.component';
import { CrisisListComponent }   from './crisis-list.component';
import { CrisisCenterComponent } from './crisis-center.component';
import { CrisisDetailGuard }     from './crisis-detail.guard';

export const CrisisCenterRoutes = [
  {
    path: '/crisis-center',
    component: CrisisCenterComponent,
    index: true,
    children: [
      { path: '', component: CrisisListComponent },
      { path: ':id', component: CrisisDetailComponent, canDeactivate: [CrisisDetailGuard] }
    ]
  }
];

and then CrisisDetailGuard looks like:

import { Injectable }    from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable }    from 'rxjs/Observable';

import { CrisisDetailComponent } from './crisis-detail.component';

@Injectable()
export class CrisisDetailGuard implements CanDeactivate<CrisisDetailComponent> {

  canDeactivate(component: CrisisDetailComponent): Observable<boolean> | boolean {
    return component.canDeactivate();
  }
}

I am guessing you can do the same with the canActivate lifecycle hook. Also this looks like a solution to get round our DI in our lifecycle hooks. So it looks like we do not have do use Brandon Roberts DI hack :)

Take a look at this indepth overview of the new routing they have been working on by Victor Savkin: http://victorsavkin.com/post/145672529346/angular-router

SOURCE (the plnkr from the article.. currently outdated): http://plnkr.co/edit/ER0tf8fpGHZiuVWB7Q07?p=preview

EDIT: uploaded highlighted code to match router.rc3



回答3:

There's the router guide for the v3 as alpha available https://angular.io/docs/ts/latest/guide/router.html, which should explain them.

if you go to https://angular.io/docs/ts/latest/guide/router.html#!#milestone-4-query-parameters and scroll slightly up there's an example which should demonstrate it :)