【发布时间】:2016-08-15 19:37:51
【问题描述】:
我有一个 Angular 2 服务,它执行几个步骤来验证和登录应用用户。每当我尝试在我的观察者上调用 next() 时,我都会收到一个未定义的错误。当 Observable 被实例化时,我唯一可以成功调用 next() 的地方是在构造函数内部。
如果我调用 authenticateUser(),我会收到 this.isLoggedIn 未定义的错误。
AuthService.ts
public isLoggedIn$: Observable<boolean>;
private isLoggedIn: Observer<boolean>;
constructor(...) {
this.isLoggedIn$ = new Observable<boolean>(
(observer: Observer<boolean>) => {
this.isLoggedIn = observer;
// this works fine
this.doLogin();
}).share()
}
private doLogin = ():void => {
let context:AuthContextModel = this.authContextService.getAuthContext();
if (context) {
let isAuthenticated = this.isAuthenticated(context);
if (isAuthenticated) {
this.doCreateCurrentUserContext(context)
.then((result) => {return this.doNotifyLoggedInStatus(result);});
}
}
};
private doNotifyLoggedInStatus = (result:boolean):Promise<boolean> => {
this.isLoggedIn.next(result);
return new Promise((resolve, reject) => {
return resolve(true);
});
};
public authenticateUser = (user: string, pass: string):Promise<boolean> => {
return this.doFetchToken(user, pass)
.then((fetchTokenData) => {return this.doStoreToken(fetchTokenData);})
.then((authContext) => {return this.doCreateCurrentUserContext(authContext);})
.then((result) => {return this.doNotifyLoggedInStatus(result);});
};
【问题讨论】:
-
我猜那是因为
isLoggedIn$没有被订阅。 -
@estus 谢谢.. 就是这样!我已经敲了几个小时的头了..谢谢!