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

时间:2016-02-19 08:44:54

标签: angular eventemitter

我有HomeCmpShared Service

查看shared service的构造函数。我手动设置了“访客”#39;字符串并尝试发出UserModel object。但它在HomeCmp ngOnInit中没有收到对象。

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

当我通过Guest运行应用时,如何显示EventEmitter字符串。

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

1 个答案:

答案 0 :(得分:1)

Angular创建一个<ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Blog</a></li> </ul>实例,在执行此操作时,将执行构造函数并触发事件。下一步,Angular创建NavService组件的实例并传递HomeCmp。然后在NavService构造函数中注册HomeCmp的侦听器。在此注册后,不会发出任何事件,因此不再接收。

你想要做的是延迟解雇事件。我假设您的情况仅用于测试目的,实际上在构造函数中触发事件并不是必需的。

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

setTimeOut

<强> Answer