簡體   English   中英

如何鏈接/組合可觀察物

[英]How to chain/combine Observables

好的,這困擾了我一段時間,想知道是否有人可以向我展示一種在多個服務之間鏈接Observable的好方法。

在下面的Auth類示例中,從this.api.postSignIn()創建Observable的一種好方法是什么,以便signInSubmit()可以在組件中重新訂閱它? 值得注意的是this.api.postSignIn()正在訂閱Angular2 http請求。

這是一種反模式嗎?是否有更好的方法可以做到這一點?

基本上,我想實現的功能是:

  • 組件-負責收集登錄數據並將其以正確的格式發送到auth服務。 然后,完成身份驗證登錄后,導航至管理頁面。
  • 服務-進行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() { } } 

我會利用docatch運算符,而不是在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM