来自路由器出口组件的 angular 2 更新应用程序组件 [英] angular 2 update app component from router outlet component

查看:16
本文介绍了来自路由器出口组件的 angular 2 更新应用程序组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular 2 rc1 和新的路由器 @angular/router

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>

我将 loginService 注入应用组件并订阅了 ngOnInit 中的事件

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;
}  

当我导航到我的/login"路由页面/组件时,我的 loginService 被注入并且 loginService 定义了一个事件

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);

我可以在订阅的 loginSucess 上的应用程序组件中设置断点并传递数据,但是this"未定义.

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

推荐答案

不确定并且数据已通过"是什么意思.

Not sure what you mean by "and the data is passed".

@Output() loginSuccess = new EventEmitter<IAuthResponse>();

在路由器添加的组件中 (LoginComponent) 不做任何事情.不支持路由组件中的 @Input()@Output().

in the component added by the router (LoginComponent) doesn't do anything. @Input() and @Output() in routed components are not supported.

只需将 LoginService 注入路由组件并使用登录组件中的 observable 发出事件.

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);
  }
}

这篇关于来自路由器出口组件的 angular 2 更新应用程序组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆