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

查看:83
本文介绍了路由器出口组件的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注入路由组件并使用登录组件中的观察对象发出事件即可.

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天全站免登陆