我一直在尋找有關如何在 Ionic 6 中獲取我的電容器存盤中的一些值并在執行 HTTP 請求之前使用它們的教程。
cart.service.ts 中的示例方法:
getCart() {
Storage.get({ key: 'token' }).then( response => {
this.token = JSON.parse(response.value);
});
return this.http.get<Product[]>(this.token.api_route 'user/cart');
}
我想在 onInit 上呼叫的內容:
this.cartService.getCart().subscribe(response => {
this.products = response;
});
所以主要問題是令牌為空,因為從存盤中獲取它是異步的。我該如何解決這個問題?并在進行 HTTP 呼叫之前獲取 token.api_route?
uj5u.com熱心網友回復:
使用 promise 而不是 observable。您可以使用 http.get(url).toPromise() 來實作這一點。
這是一個例子:
import { Component } from '@angular/core';
import { Storage } from '@capacitor/storage';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
html = 'hello';
constructor(public http: HttpClient) {}
async test() {
await this.saveToStorage();
this.problem();
}
async saveToStorage() {
console.log('Saving something to local storage...');
await Storage.set({
key: 'url',
value: 'https://jsonplaceholder.typicode.com/posts',
});
}
problem() {
this.getApiValue().then((value) => {
this.html = JSON.stringify(value) ;
});
}
async getApiValue() {
const urltogo = await Storage.get({key:'url'});
return this.http.get(urltogo.value).toPromise();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/445667.html
