簡體   English   中英

處理Angular4 Http Obserable響應的最佳實踐

[英]Best practices for handling Angular4 Http Obserable responses

我有編寫C#和Angular1代碼的經驗,但是Angular2 +和RxJ對我來說是新手。

我剛剛編寫了一個Angular4登錄組件,感覺就像是通過在可觀察對象的map函數中緩存login方法的結果來編寫代碼氣味。

我有一個AuthenticationService,LoginComponent調用登錄:

  login(username: string, password: string): Observable<User> {
return this.http
  .post('/api/users/login', { username: username, password: password })
  .map((response: Response) => {

    let loginResult = response.json();
    this.user = loginResult.user as User

    localStorage.setItem(tokenStorageName, loginResult.token);

    return this.user;
  })
  .catch(this.handleError);

}

將狀態保存在map函數中感覺很奇怪,因為據我所知,這應該只是一個轉換函數。 我想緩存從登錄結果返回的用戶和​​令牌,這樣,如果我想要用戶數據,就不必進行其他服務調用。

這是登錄組件的邏輯:

  login() {
this.isLoading = true;
this.authenticationService.login(this.model.username, this.model.password)
  .subscribe(
  result => {
    let returnUrl = this.activatedRoute.snapshot.queryParams['returnUrl'] || '/'
    this.router.navigate([returnUrl]);
  }, error => {
    if (error != null && error.code == unauthorizedCode) {
      this.error = 'Username or password incorrect';
    }
    else {
      this.error = 'Error logging in';
    }
    this.isLoading = false;
  });

LoginComponent也不能在AuthenticationService或UserCache上調用setUser。

有人可以給我一些關於最佳做法的建議嗎?

嘗試類似:

login(username: string, password: string): Observable<User> {
    let o = this.http
        .post('/api/users/login', { username: username, password: password})
    //uncomment if you have multiple subscribers, otherwise http request is executed multiple times
        //.share()
    ;

    o.subscribe(
        (response: Response) => {
            this.user = loginResult.user as User;
            localStorage.setItem(tokenStorageName, loginResult.token);
        },
        (response: Response) => this.handleError(response)
    );

    return o.map(response: Response =>  response.json());
}

托德·莫托(Todd Motto)通過Twitter舉了一個很好的例子:

https://twitter.com/toddmotto/status/865531009638440961

“在這里,單個狀態存儲非常方便-您可以使用.do(next => / *使用此值* /)完成代碼,從而完成代碼”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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