在Angular 4.3中使用新的HttpClient模塊時,從REST api獲取單個記錄時出現控制檯錯誤。我在IDE中沒有收到任何linter錯誤,頁面渲染和變量顯示。我是否聲明瞭錯誤的變量類型?Angular 4.3 HttpClient控制檯錯誤
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Hero {
id: number;
name: string;
}
@Component({
selector: 'app-root',
template: `
My name is {{hero.name}} and my id is {{hero.id}}
`})
export class AppComponent implements OnInit {
hero: Hero;
constructor(private http: HttpClient) { }
getOne() {
this.http.get<Hero>
('http://0.0.0.0:3000/api/heroes/23')
.subscribe(data => {
this.hero = data;
});
}
ngOnInit() {
this.getOne();
}
}
回報:我的名字是Bombasto,我的ID是13
與控制檯錯誤:
TypeError: undefined is not an object (evaluating '_co.hero.name')
而第一個鍵產生一個錯誤,第二個沒有(例如沒有錯誤爲hero.id)。如果我切換順序(hero.id是第一個,所以輸出是「我的ID是13,我的名字是Bombasto),我得到的是hero.id的錯誤,而不是hero.name。
隨着頁面呈現,我可以忽略控制檯錯誤並繼續前進,我試圖通過將代碼剝離到最低限度以瞭解其工作原理,並且我不想開發任何編碼習慣。
此外,與GETALL()相同的例子使用沒有任何錯誤:
heroes: Hero[];
getAll() {
this.http.get<Hero[]>
('http://0.0.0.0:3000/api/heroes')
.subscribe(data => {
console.log(data);
this.heroes = data;
});
}
感謝,
嘗試初始化英雄或將* ngIf =「hero」添加到您的節點。 –
這兩個選項都可以清除錯誤。或者,我也可以'.subscribe(data => {this.hero.id = data.id; this.hero.name = data.name;}以避免錯誤,但是試圖最小化我的代碼。謝謝, – nicolas0001
* ngIf =「英雄」似乎是最乾淨的答案,因爲它不會在HTTP調用返回之前在屏幕上刷新已初始化的變量。 – nicolas0001