我有auth警卫服务
constructor(private _auth: AuthService, private _router: Router) { }
canActivate() {
if(this._auth.isLoggedIn()){
return true;
} else {
this._router.navigate(['/login']);
return false;
}
}
那是我的isloggedin方法
isLoggedIn(): boolean {
return this._session.sessionId.length > 0;
}
并登录
login(user: User): any {
return this._http.post(this.authUrl, user)
.subscribe(x => {
this._session.sessionId = x.sessionId;
this._session.name = x.username;
});
}
我的问题是,登录后首先检查isloggedin
,我认为这是因为subscribe
(登录方法等待来自服务器的响应)
所以我在asObservable.first()
isLoggedIn
isLoggedIn(): boolean {
return (this._session.sessionId.length > 0).asObservable().first();
}
但它会在控制台中登录
属性'asObservable'在类型'boolean'上不存在。
我该如何解决?
答案 0 :(得分:0)
如果您subscribe()
,则通话会返回Subscription
而不是Observable
从您的问题中不清楚login()
应该做什么,但是因为return
_http.post()
电话的结果我怀疑您确实想要返回Observable
。为此,您需要将subscribe
更改为map
(需要导入map
):
login(user: User): any {
return this._http.post(this.authUrl, user)
.map(x => {
this._session.sessionId = x.sessionId;
this._session.name = x.username;
});
}
<强>更新强>
constructor(private _auth: AuthService, private _router: Router) { }
loggedIn = new Subject();
login(user: User): any {
return this._http.post(this.authUrl, user)
.map(x => {
this._session.sessionId = x.sessionId;
this._session.name = x.username;
this.loggedIn.next(true);
});
}
canActivate() {
return loggedIn.map(loggedIn => {
if(this._auth.isLoggedIn()){
return true;
} else {
this._router.navigate(['/login']);
return false;
}
});
}