【问题标题】:angular2 : issue with rest apiangular2:rest api的问题
【发布时间】:2016-11-01 15:46:48
【问题描述】:

我正在尝试学习angular2(来自php脚本,这很困难^^),在“英雄之旅”中使用真正的rest api。 根据我的阅读,我认为这可能很简单......

我有一个使用 Express 构建的工作 api:

curl -XGET http://localhost:3001/heroes
[{"_id":"58185c8a8af4b512c51c0519","no":"1","name":"bahamut","__v":0,"updated_at":"2016-11-01T09:12:42.803Z"},{"_id":"58185ca78af4b512c51c051a","no":"2","name":"gatz","__v":0,"updated_at":"2016-11-01T09:13:11.063Z"},{"_id":"58185ec98af4b512c51c051b","no":"3","nam...

在 hero.service.ts 中,我可以得到数据:

getHeroes(): Promise<Hero[]> { // {{{
    console.log('getheroes in service');
    console.log( "%o", this.http.get(this.heroesUrl).toPromise()); 
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  } // }}}

console screenshot

当我在原始“英雄之旅”上执行相同的 console.log 时,我有一个数据数组,而这里我有一个字符串...... 我想我必须在某个地方转换字符串,但无论我尝试了什么,它都不起作用。

(我也读过很多关于 Observable 的例子,但我也没有成功)

帮我解释一下如何... TIA

日本

【问题讨论】:

标签: javascript rest angular


【解决方案1】:

你离得太近了!这里的错误在于你如何处理 Promises,以及误解它们如何返回。在这种情况下,当您打算将 response.json() 强制转换为 Hero[] 类型然后返回时,您试图分配一个未定义的属性 (response.json().data)。

您需要做的是确保在使用 json() 调用将响应转换为 JSON 时分配匹配的类型。指南中的Hero 类型与您的响应不匹配,因此您会遇到错误。

要检查您是否收到响应,请调用服务的 getHeroes() 函数并记录返回值。可以在函数内部进行日志记录,但这将是深入了解 Promises 如何工作的地方。

getHeroes(): Promise<Hero[]> {

    return this.http.get(this.heroesUrl)
               .toPromise()
               .then((response) => response.json() as Hero[])
               .catch(this.handleError);
}

如果你想知道我没有疯,这里是内部记录的代码。无论收到什么类型的回复,这都会记录您的回复。

getHeroes(): Promise<Hero[]> {

    return this.http.get(this.heroesUrl)
               .toPromise()
               .then((response) => {
                 console.log(response.json());
               })
               .catch(this.handleError);
}

要进一步了解为什么要执行这些 then() 调用,Promise 会异步返回,这意味着结果仅在经过不确定的时间后才可用。任何必须等待结果的执行必须要么发生在then() 调用中,要么发生在函数返回实际值之后。由于 JS 函数同步运行,如果您尝试执行以下示例,您将看到打印输出 undefined 而不是字符串响应。这是因为 console.log(r) 在 promise 调用之后立即被调用,完全没有注意到它实际上并没有让 r 被赋值。

getHeroes(): Promise<Hero[]> {
      var r;
      this.http.get(this.heroesUrl)
               .toPromise()
               .then((response) => r = response.json())
               .catch(this.handleError);
      console.log(r);

}

【讨论】:

  • 令人印象深刻!你很快解决了我的问题。甚至有些点比较清楚了,js和()之类的还是要多学点……(比如我不知道json()是从哪里来的)。
猜你喜欢
  • 1970-01-01
  • 2016-05-14
  • 2020-08-17
  • 1970-01-01
  • 2017-01-23
  • 2017-10-17
  • 2019-05-22
  • 1970-01-01
相关资源
最近更新 更多