共享服务构造函数中的 EventEmitter 不发射数据

EventEmitter in shared service's constructor doens't emit data

我有一个 HomeCmpShared Service

查看 shared service 的构造函数。我已手动设置 'Guest' 字符串并尝试发出 UserModel object。但是它没有在 HomeCmpngOnInit.

中接收对象

如果您单击该按钮,它将起作用。有什么建议吗?

当我通过 EventEmitter.

运行 应用程序时,如何显示 Guest 字符串

service.ts

import {EventEmitter} from 'angular2/core';
import {UserModel} from 'app/models';
export class NavService {

  user:EventEmitter<UserModel>=new EventEmitter();
  constructor() {
    console.log('constructor')

    userDetail=new UserModel();
    userDetail.name="guest";
    userDetail.loggedIn=false;
    console.log(userDetail);
    this.user.emit(userDetail);
  }

  ngOnInit(){ // just wanted to check if it could help or not. I know it belongs to Component's life cycle.
    console.log('onit')
  }

   setUserDetail(str)
  {
    console.log('SetUserDetail started');
    userDetail.name=str;
    userDetail.loggedIn=true;
    this.user.emit(userDetail);
  }

  getUserDetail()
  {
    return this.user;
  }
}

Homecmp.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';
import {UserModel} from 'app/models';

@Component({
  selector: 'my-app',
  template: `<div>User object:</div>

  {{userData|json}}
  <button (click)="setuser()">Click</button>
  `
})
export class HomeCmp {
  constructor(authService:NavService){
        this.authService=authService; 

    }
  setuser()
  {
   this.authService.setUserDetail("micronyks");
  }


     ngOnInit(){
                console.log('here is userInfo');
                this.subscription = this.authService.getUserDetail()
                                    .subscribe((item) => {this.userData=item;
                                                          console.log('Finally i m working');
                                                          console.log(this.userInfo);

                                                         });
     }

    ngOnDestroy() {

    }
}

models.ts

export class UserModel()
{
 private name:string;
 private loggedIn:boolean=false;
}

working Demo

Angular 创建一个 NavService 实例,并在执行此操作时执行构造函数并触发事件。下一步 Angular 创建 HomeCmp 组件的实例并将 NavService 传入。然后在 HomeCmp 的构造函数中注册 user:EventEmitter 的侦听器。注册后没有事件发出,因此不再收到。

您想做的是延迟触发事件。我假设您的情况仅用于测试目的,实际上无论如何都不需要在构造函数中触发事件。

出于测试目的,您可以将 this.user.emit(userDetail); 包装在 setTimeOut

setTimeOut(() => this.user.emit(userDetail), 1);

Answer