成功登錄后,我需要在本地存盤中存盤一些值。
我的 API 回傳這個
{
"auth": {
"name": "FooBar",
"username: 'foobaz",
},
"token": "1234567890abcdefghijklmnop"
}
我試過在里面做這個login(),authentication.service.ts但我想不通。我已經嘗試(在許多其他事情中)switchMap在內部多次使用,但pipe()成功率為零。
身份驗證.service.ts
login(credentials: { email: any, password: any }): Observable<any> {
return this.http.post('https://mysite.test/api/login', credentials)
.pipe(
map((data: any) => data.token),
switchMap(token => {
return from(Preferences.set({ key: 'token', value: token }));
}),
tap(_ => {
this.isAuthenticated.next(true);
})
)
}
所以我想我會在里面嘗試.subscribe(),login.page.ts但我一直收到錯誤,比如TypeError: undefined is not an object (evaluating 'res.auth.name').
顯然存在;我正在使用await,而且當出現錯誤時,我能夠res.error.message從 API 獲取和讀取訊息,所以我真的很困惑我做錯了什么?
我想也許我需要map()再次獲得結果,但我無法讓它發揮作用。我找不到展示如何做我想做的事的例子。
登錄頁面.ts
async login() {
const loading = await this.loadingController.create();
await loading.present();
this.authService.login(this.myForm.value)
.subscribe(
async (res:any) => {
// THIS IS WHAT I'M TRYING TO ACCOMPLISH
await Preferences.set({ key: 'authName', value: res.auth.name });
await Preferences.set({ key: 'authUsername', value: res.auth.username });
await loading.dismiss();
this.menu.enable(true);
this.router.navigateByUrl('/tabs/home', { replaceUrl: true });
},
async (res) => {
await loading.dismiss();
const alert = await this.alertController.create({
header: 'Login Failed',
message: res.error.message,
buttons: ['OK'],
});
await alert.present();
}
);
}
uj5u.com熱心網友回復:
我相信問題出在switchMap您創建并回傳另一個覆寫原始 Observable 的新 Observable 的運算子上。
建議在運算子中執行Preferences.set操作tap以保持原始 Observable 值。
login(credentials: { email: any, password: any }): Observable<any> {
return this.http.post('https://mysite.test/api/login', credentials)
.pipe(
tap((data: any) => {
Preferences.set({ key: 'token', value: data.token });
this.isAuthenticated.next(true);
})
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/504174.html
