我在當前專案中使用 Angular 9.0.7。我有一個用 Node.js (Express) 撰寫的后端和一個用 Angular 撰寫的前端。
我遇到的問題是我的服務沒有呼叫處理后端請求以在第一次加載時檢索資料的函式,但是如果我重繪 頁面它確實可以作業。
我有一個 deviceService.ts 檔案,用于處理與設備相關的所有請求。我有一個獲取請求來檢索我在資料庫中擁有的所有設備。正在加載身份驗證令牌,我可以看到它,設備請求在初始加載時沒有通過。deviceService.ts 檔案的函式如下所示:
getAllDevices(){
this.authenticationService.login(this.username, this.password);
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'auth-token': localStorage.getItem('auth-token')
});
const options = { headers };
return this.http.get(`${environment.apiUrl}/pm/devices?pa_id=${this.pm_id}`, options);
}
然后我正在做的是將我從此請求收到的設備添加到我使用它的組件中稱為設備的 localStorage。該組件在初始加載時出現在主頁上。該函式如下所示:
ngOnInit(): void {
this.deviceService.getAllDevices().subscribe(data => {
let temp_devices = [];
data['devices'].forEach(device => {
device.supported_memory.forEach(memory => {
var o = Object.assign({}, device);
var model_manufacturer = device.manufacturer " " device.model " " memory;
var phone_image = device.manufacturer " " device.model;
phone_image = phone_image.replace(/\s/g, '');
o.phone_image = phone_image.toLowerCase();
o.model_manufacturer = model_manufacturer;
o.memory = memory;
temp_devices.push(o);
});
});
this.devices = temp_devices;
this.devices = temp_devices.map(function(el, i, array){
var o = Object.assign({}, el);
return o;
});
localStorage.setItem('devices', JSON.stringify(this.devices));
});
}
如上所述,我不明白為什么請求沒有在初始加載時被呼叫,而是在第二次被呼叫。
uj5u.com熱心網友回復:
這是因為this.authenticationService.login(this.username, this.password);是異步的。因此,當您呼叫 getAllDevices 第一次加載頁面時,令牌不可用。您可以通過檢查 devTools 控制臺來確認它。
getAllDevices(){
this.authenticationService.login(this.username, this.password);
// rest code will continue to execute but token will be null
}
第二次加載頁面,您沒有看到問題,因為令牌已經存在于本地存盤中。
解決方案:當令牌已經可用時,您應該呼叫 getAllDevices。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/408144.html
標籤:
