在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