I'm using angular 2 rc1 and the new router @angular/router
In app component I have a nav section and router outlet
<nav>
<a *ngIf="auth?.userName == null" [routerLink]="['/login']">Login</a>
<a *ngIf="auth?.userName != null" (click)="logout()">Logout</a>
{{auth?.userName}}
</nav>
<router-outlet></router-outlet>
I inject a loginService into app component and subscribe to an event in ngOnInit
ngOnInit() {
this.loginService.loginSuccess.subscribe(this.loginSuccess);
}
ngOnDestroy() {
this.loginService.loginSuccess.unsubscribe();
}
private loginSuccess(res: IAuthResponse) {
this.auth = res;
}
when I navigate to my '/login' route page/component my loginService is inject and loginService defines an event
@Output() loginSuccess = new EventEmitter<IAuthResponse>();
and after successful login in my service, the login service raises the event
this.loginSuccess.next(response);
I'm able to set a breakpoint in app component on the subscribed loginSucess and the data is passed along, however 'this' is undefined.
private loginSuccess(res: IAuthResponse) {
this.auth = res; //this is undefind
}
how can I update the app component from events that are triggerd from services used in components that are hosted in the router outlet
You can add multiple outlets in your Angular application which enables you to implement advanced routing scenarios. Any component that gets matched by the Router will render it as a sibling of the Router outlet.
You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows.
What is an activated route? The Angular Docs define the ActivatedRoute as. A service that is provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query params and the global fragment.
Not sure what you mean by "and the data is passed".
@Output() loginSuccess = new EventEmitter<IAuthResponse>();
in the component added by the router (LoginComponent
) doesn't do anything.
@Input()
and @Output()
in routed components are not supported.
Just inject LoginService
to the routed component and emit the event using an observable in the login component.
@Injectable()
export class LoginService {
changes:BehaviorSubject = new BehaviorSubject(false);
}
export class LoginComponent {
constructor(private loginService:LoginService) {}
onLogin() {
this.loginService.changes.next(true);
}
}
export class NavComponent {
constructor(private loginService:LoginService) {}
onLogin() {
this.loginService.changes.subscribe(status => this.isLoggedIn = status);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With