2016-03-24 66 views
2

爲了使用角度2和rxjs,我遇到了問題。瞭解角度和HTTP的rxjs

我試着做一個基本的登錄:這裏是代碼:

class LoginPage{ 
    ctor(private auth:AuthService) {} 

    login(cred) { 
     this.auth.login(cred).subscribe(res=> this.navigateToHome() 
    } 
} 

class AuthService { 
    ctor(private http:AuthHttp) {} 

    login(cred){ 
     return this.http.post(url, cred).subscribe(res => this.onLoginSuccess()) 

    } 
} 

class AuthHttp extends Http { 
    ctor (.....) 

    post(...) { 
    // Add some headers 
     return super.post(..) 
    } 
} 

現在首先是不會工作的,因爲在AuthServicelogin現在返回Subscription對象,而不是一個Observable,在addtional如果拿在login功能和重構它這樣:

login(cred) { 
    var obs = this.http.post(url, cred) 
    obs.subscribe(res=> this.onLoginSuccess()) 
    retrun obs 
} 

這會導致HTTP請求來調用兩次..

所以我的問題是:我怎麼知道我的loginPage調用onLoginSuccess的用戶完成了?

我該如何避免2次請求?

回答

3

share()怎麼樣?

如果您需要訂閱AuthService.login(),那麼login()必須返回Observable。但你也需要在AuthService裏面登錄,不是嗎? share()讓您在登錄AuthService時訂閱並返回Observable

class AuthService { 
    ctor(private http:AuthHttp) {} 

    login(cred){ 
     var result = this.http.post(url, cred).share(); 
     result.subscribe(res => this.onLoginSuccess()) 
     return result; 
    } 
} 
+0

請分享一些更多詳情?這和'do'有什麼區別? – tubu13