Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

router

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.

like image 362
Juergen Zimmermann Avatar asked Jun 10 '16 14:06

Juergen Zimmermann


2 Answers

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

like image 127
Nige Avatar answered Sep 19 '22 06:09

Nige


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

like image 21
Matt B Avatar answered Sep 22 '22 06:09

Matt B