簡體   English   中英

如何使用 angular pipe 並在請求調用中正確訂閱

[英]how to use angular pipe and subscribe correctly in request call

在我的 angular 應用程序中,我向后端發送請求以檢查憑據,成功后后端發送一個我讀取的令牌。 到目前為止,這是有效的,但我必須使用 pipe 將它變成 map 到一個方法,然后使其工作。 但我現在的問題是,即使我從服務器獲得 200,我的頁面也不會自動導航到受保護的頁面。 如果我手動輸入 url 它會起作用,這就是我嘗試過的:

  authenticateUser(login: LoginModel){
    this.http = new HttpClient(this.handler)
    return this.http.post<JwtToken>(environment.rootUrl + 'api/authenticate', {
      username: login.username,
      password: login.password,
    }).pipe(map(response => this.authenticateSuccess(response)))
      .subscribe({
        next: () => {
          this.isAuthenticated = true;
          this.router.navigate(['/dashboard'])
        }, error: (error) => {
          this.isAuthenticated = false;
          console.log(error)
        }
      })

  }

它在pipe之后沒有進入訂閱部分。有什么辦法可以使這個工作嗎? 我仍然希望有一個錯誤處理,如果沒有錯誤則導航到 url 如果錯誤不導航。

編輯:

驗證成功方法:

  isUserLoggedIn(){
    return !! localStorage.getItem('authenticationToken')
  }

  private authenticateSuccess(response: JwtToken): void {
      const jwt = response.id_token;
      localStorage.setItem('authenticationToken' , jwt)
      this.localStorageService.store('authenticationToken', jwt);
      console.log(this.localStorageService.retrieve('authenticationToken'))
      this.sessionStorageService.clear('authenticationToken');

  }

授權衛士:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    private auth: AuthenticationService,
    private router: Router
  ) {
  }

  canActivate(): Promise<boolean> {
    return new Promise(resolve => {
      if (this.auth.isUserLoggedIn()) {
        resolve(true)
      } else {
        this.router.navigate(['authenticate'])
        resolve(false)
      }
    })

  }
}

解決方案:

 authenticateUser(login: LoginModel) {
    this.http = new HttpClient(this.handler)
    return this.http.post<JwtToken>(environment.rootUrl + 'api/authenticate', {
      username: login.username,
      password: login.password,
    }).subscribe({
      next: response => {
        this.isAuthenticated = true;
        this.authenticateSuccess(response)
        this.router.navigate(['/dashboard'])
      }, error: (err) => {
        console.log(err)
      }, complete: () => {
        console.log("finished without worry")
      }
    })
  }

RxJs map運算符應該修改可觀察對象的內容。 然而, map運算符需要返回相同的可觀察值或另一個可觀察值,以便下一個subscribe操作能夠 function。

在您的情況下,您的map運算符根本不返回任何可觀察值,因此沒有理由觸發subscribe方法。

您可以在此處的方法中再次簡單地返回response

private authenticateSuccess(response: JwtToken): any {
      const jwt = response.id_token;
      localStorage.setItem('authenticationToken' , jwt)
      this.localStorageService.store('authenticationToken', jwt);
      console.log(this.localStorageService.retrieve('authenticationToken'))
      this.sessionStorageService.clear('authenticationToken');
      return response;
  }

但我認為map方法的所有代碼直接在subscribe方法中匹配得更好。

暫無
暫無

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

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