![](/img/trans.png)
[英]How to use a Service that executes HTTP request inside an 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.