在 Angular2 中使用事件发射器在服务和组件之间共享数据

Using event emitter in Angular2 to share data between service and component

我有一个 angular2 应用程序,其中有一个登录页面。登录后,我想在header组件中显示用户名。

    @Output() getUserName = new EventEmitter();

在服务的认证方法中

authenticate(loginRequest)  {
    let headers = new Headers({ 'Content-Type' : 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let authenticateResp = this.http.post("http://localhost:8080/authenticate", JSON.stringify(loginRequest), options).map(result => result.json());
    authenticateResp.subscribe((authenticate => {
        this.getUserName.emit("My Name");
    }));    

    return authenticateResp; 
}

构造函数中的header组件

@Component({
 .....
 providers:[LoginService]
})
export class HeaderComponent {
  userName : string;
  constructor(private loginService : LoginService) { 

      loginService.getUserName.subscribe(authenticated => this.setName(authenticated));
  }

  setName(authenticated) {
    this.userName = authenticated;
  }

}

当我调试时,我可以看到事件发射代码被执行,但组件中订阅的代码没有被调用。我在这里做错了什么?

感谢任何帮助

@Output()EventEmitter 不能在服务内部使用,因为它们是 .

EventEmitter 是(目前)Subject 的子类,一个标准的 Subject,不会在内存中保留最新发出的值,因此如果在内存中发出一个值没有订阅者,该值被忽略了。

A ReplaySubject 将向任何新订阅者重复最后发出的值。

备注:

  • 最好只公开 Observable 而不是 Subject
  • 您不想在 authenticate 方法中同时订阅 authenticateResp 和 return authenticateResp,因为如果您这样做会触发两次请求订阅 returned 值。您应该使用 do() 运算符,return observable 并在需要该数据的地方订阅。
private _userName = new ReplaySubject<string>();

userName=this._userName.asObservable();

authenticate(loginRequest)  {
    let headers = new Headers({ 'Content-Type' : 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post("http://localhost:8080/authenticate", JSON.stringify(loginRequest), options)
        .map(result => result.json())
        .do((authenticate => this._userName.next("My Name")));    
}

在你的组件中:

loginService.userName.subscribe(authenticated => this.setName(authenticated));