我创建了一个身份验证服务,组件可以订阅权限更改(登录/注销/Angular 色更改等)。 在 isAuthenticated 函数中,我返回一个主题。 问题是我想用一个值返回主题(比如 Observable.of。现在,我正在使用 setTimeout。
@Injectable()
export class AuthenticationService {
constructor(private credentials: CredantialsStorageService,
private oauthService:OAuth2Service,
private secureHttp: SecureHttpService) {}
private isAuthenticatedSubject: Subject<boolean> = new Subject<boolean>();
login(email:string, password: string, remember?:boolean ): Observable<boolean> {
return this.oauthService.login(email, password)
.flatMap(() => this.getAndStoreUserCredantials())
.map((userCredantials: any) => {
this.isAuthenticatedSubject.next(true);
return true;
})
}
logout(): Observable<void> {
return this.secureHttp.post('/logout', null)
.finally(() => {
this.credentials.clear();
this.oauthService.clear();
this.isAuthenticatedSubject.next(false);
})
.map(() => null);
}
isAuthenticated(): Observable<boolean> {
setTimeout(() => { //Hack - find a way to change this
this.isAuthenticatedSubject.next(this.oauthService.isAuthenticated());
})
return this.isAuthenticatedSubject;
}
private getAndStoreUserCredantials() {
return this.secureHttp.get('/user/info')
.map((res:Response) => {
let userCredantials = res.json();
this.credentials.set(userCredantials);
return userCredantials;
})
}
}
最佳答案
我认为最简单的方法是使用 startWith()
运算符:
isAuthenticated(): Observable<boolean> {
return this.isAuthenticatedSubject.startWith(this.oauthService.isAuthenticated());
}
您也可以使用 BehaviorSubject
或 ReplaySubject
但它们只会重复已经通过它们的值。也许还可以查看此答案以获取更详细的描述有什么区别:Does startWith() operator turns Observable into ReplaySubject(1)? .
关于angular - RxJS - 返回具有值(value)的主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45400444/