【发布时间】:2016-12-25 18:44:42
【问题描述】:
我正在构建来自https://angular.io/docs/ts/latest/tutorial/的英雄之旅。
完整的教程运行良好,我制作了一个 nodejs api 来处理后端。 目前我有一个工作后端,英雄之旅前端可以调用它来检索完整的英雄列表、查看英雄、更新英雄和删除英雄。
我的问题是,当我尝试添加英雄时。 执行此操作的 nodejs 代码如下所示:
function createBox(req, res, next) {
req.body.age = parseInt(req.body.age);
db.none('insert into boxes(name, description)' +
'values(${name}, ${description})',
req.body)
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one box'
});
})
.catch(function (err) {
return next(err);
});
}
heros.component.ts 中处理英雄添加的方法如下所示:
add(name: string, description: string): void {
name = name.trim();
description = description.trim();
if (!name) { return; }
this.heroService.create(name,description)
.then(hero => {
this.heroes.push(hero);
this.selectedHero = null;
});
}
}
添加英雄时,数组会填充一个空项目,控制台显示以下错误:
异常:http://192.168.4.13:3001/app/heroes/heroes.component.html:14:24 中的错误由以下原因引起:无法读取未定义的属性“id”
heroes.component.html 中第 14 行的代码如下所示:
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}} {{hero.description}}
<button class="delete"(click)="delete(hero); $event.stopPropagation()">x</button>
</li>
</ul>
第 14 行是这一行:
<span class="badge">{{hero.id}}</span> {{hero.name}} {{hero.description}}
我怀疑该错误是由于新后端在将新创建的英雄的值添加到数据库后没有将其发送回客户端的速度很快,就像angular-in-memory-api 所做的那样,但我没有不知道是不是这样。我已经玩了一段时间了,没有任何运气。
有什么想法吗?
【问题讨论】:
-
尝试像这样
{{hero?.id}}使用安全导航运算符 (?) -
这导致浏览器控制台不显示错误,但添加的元素在列表中仍然是空的(后端处理它很好,并将其添加到数据库中)。
-
.then(hero => { console.log(hero);..记录什么? -
未定义 hero.component.ts:54 未定义
-
这意味着你的
this.heroService.create服务没有返回任何东西。所以如果hero是undefined,你不能指望它显示任何东西。