【问题标题】:Angular2 tour of heroes tutorial calling nodejs backendAngular2英雄之旅调用nodejs后端教程
【发布时间】: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 =&gt; { console.log(hero);.. 记录什么?
  • 未定义 hero.component.ts:54 未定义
  • 这意味着你的this.heroService.create 服务没有返回任何东西。所以如果heroundefined,你不能指望它显示任何东西。

标签: node.js angular


【解决方案1】:

正如我们在评论部分所讨论的。您来自后端的值并没有像您预期的那样出现。

因此,安全导航操作员 (?) 不会使用 {{hero?.id}} 打印任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多