我正在使用Observable和EventEmitter,您可以在http://plnkr.co/edit/HV2sWd?p=preview找到完整的代码
即使使用publishReplay,它也不起作用:(
我怀疑是EventEmitter.asObservable()
我缺少什么?
auth-service.ts:
@Injectable()
export class AuthService {
private _isLoggedIn: boolean = false;
private _isLoggedInEvent: EventEmitter<boolean>;
private _isLoggedInObservable: Observable<boolean>;
constructor(){
this._isLoggedInEvent = new EventEmitter<boolean>();
this._isLoggedInObservable = this._isLoggedInEvent.asObservable().publishReplay(1);
this._isLoggedInEvent.emit(false);
}
login() {
return Observable.of(true).delay(1000).do(val =>{
this.isLoggedIn = true;
this.isLoggedInEvent.emit(true);
});
}
logout() {
this.isLoggedIn = false;
}
isLoggedInObservable() : Observable<boolean> {
return this._isLoggedInObservable;
}
}
答案 0 :(得分:0)
最后我用BehaviorSubject代替事件发射器并且工作 这是解决方案docs
@Injectable()
export class AuthService {
private _isLoggedIn: boolean = false;
private _isLoggedInEvent: BehaviorSubject<boolean>;
private _isLoggedInObservable: Observable<boolean>;
constructor(){
this._isLoggedInEvent = new BehaviorSubject<boolean>(false);
this._isLoggedInObservable = this._isLoggedInEvent.asObservable();
//this._isLoggedInEvent.next(false);
}
login() {
return Observable.of(true).delay(1000).do(val =>{
this.isLoggedIn = true;
this.isLoggedInEvent.next(true);
});
}
logout() {
this.isLoggedIn = false;
}
isLoggedInObservable() : Observable<boolean> {
return this._isLoggedInObservable;
}
}