问题
I have a HomeCmp
and Shared Service
.
Look at the shared service
's constructor. I have manually set 'Guest' string and trying to emit UserModel object
. But it doesn't receive object in HomeCmp
's ngOnInit
.
If you click the button, it will work. any suggestion?
How can I show Guest
string when I run the app through 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:
Angular creates a NavService
instance and while doing this, the constructor is executed and the event fired. As next step Angular creates an instance of the HomeCmp
component and passes the NavService
in. Then in HomeCmp
s constructor a listener for user:EventEmitter
is registered. After this registration no event is emitted and therefore not recieved anymore.
What you want to do is to delay firing the event. I assume your situation is only for testing purposes and in practice firing an event in the constructor isn't necessary anyway.
For testing purposes you can just wrap this.user.emit(userDetail);
in a setTimeOut
setTimeOut(() => this.user.emit(userDetail), 1);
Answer
来源:https://stackoverflow.com/questions/35500890/eventemitter-in-shared-services-constructor-doenst-emit-data