[英]How to chain/combine Observables
好的,這困擾了我一段時間,想知道是否有人可以向我展示一種在多個服務之間鏈接Observable的好方法。
在下面的Auth類示例中,從this.api.postSignIn()
創建Observable的一種好方法是什么,以便signInSubmit()
可以在組件中重新訂閱它? 值得注意的是this.api.postSignIn()
正在訂閱Angular2 http請求。
這是一種反模式嗎?是否有更好的方法可以做到這一點?
基本上,我想實現的功能是:
服務-進行api調用以獲取令牌,通過令牌服務設置令牌並設置isSignedIn
bool,然后將控制權交還給調用組件。
@Component({...}) export class SignIn { private signIn:SignInModel = new SignInModel(); constructor(private auth:Auth, private router:Router) { } ngOnInit() { } signInSubmit() { this.auth.signIn(this.signIn) .subscribe( () => { this.router.navigate(['/admin']); } ) } } @Injectable() export class Auth { private isSignedIn:boolean = false; constructor(private api:Api, private tokenService:TokenService) { } public signIn(signIn:SignInModel) { return this.api.postSignIn(signIn) .subscribe( response => { this.tokenService.set(new TokenModel(response.token)); this.isSignedIn = true; }, error => { console.log(error); } ); } public signOut() { } }
我會利用do
和catch
運算符,而不是在signIn
方法中進行訂閱。
這是重構的signIn
方法:
public signIn(signIn:SignInModel) {
return this.api.postSignIn(signIn)
.do(
response => {
this.tokenService.set(new TokenModel(response.token));
this.isSignedIn = true;
})
.catch(
error => {
console.log(error);
}
);
}
你的情況,你不能這個方法返回的對象,因為訂閱subscribe
方法返回一個訂閱,而不是一個可觀察的。 所以你不能訂閱...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.