Skip to content

Instantly share code, notes, and snippets.

@pjlamb12
Created April 28, 2016 04:51
Show Gist options
  • Save pjlamb12/9fa125c27d03c176ee33c7672033ceb4 to your computer and use it in GitHub Desktop.
Save pjlamb12/9fa125c27d03c176ee33c7672033ceb4 to your computer and use it in GitHub Desktop.
ngOnInit not firing when using router.navigate()
import {Directive, ElementRef, DynamicComponentLoader, Attribute} from 'angular2/core';
import {RouterOutlet, Router, ComponentInstruction} from 'angular2/router';
import {Session} from '../services/session';
@Directive({
selector: 'auth-router-outlet'
})
export class AuthenticatedRouterOutlet extends RouterOutlet {
publicRoutes: string[];
private parentRouter: Router;
private session: Session;
constructor(
_elementRef: ElementRef,
_loader: DynamicComponentLoader,
_parentRouter: Router,
@Attribute('name') nameAttr: string,
_session: Session
){
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
this.session = _session;
this.publicRoutes = [
''
]
}
activate(instruction: ComponentInstruction) {
if(instruction.urlPath == '' && this.session.loggedIn()) {
this.parentRouter.navigate(['Dashboard']);
} else if(instruction.urlPath != '' && !this.session.loggedIn()) {
this.parentRouter.navigate(['Home']);
} else {
return super.activate(instruction);
}
}
_canActivate(url) {
console.log('loggedIn: ', this.session.loggedIn());
return this.publicRoutes.indexOf(url) !== -1 || !this.session.loggedIn();
}
}
import {Component, OnInit, NgZone} from 'angular2/core';
import {Session} from '../../services/session';
import {UserService} from '../../services/user';
import {tokenNotExpired} from 'angular2-jwt';
@Component({
selector: 'dashboad',
templateUrl: '/components/dashboard/dashboard.html',
providers: [UserService]
})
export class Dashboard implements OnInit {
public user: any;
constructor(private _user: UserService, private _session: Session, private _ngZone: NgZone) {}
ngOnInit() {
console.log('in the onInit method');
this._user.getUser().subscribe(data => {
this.user = data;
this._ngZone.run(() => { }); //I've tried with and without this part. Neither works.
});
}
showDiv() {
if(this.user) {
console.log('showing')
return this.user.attribute; //This is what I want to check to see if the div should be shown or not
} else {
console.log('not showing')
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment