【问题标题】:Angular 2 RxJs Promise not working for http.get call to C# Controller whereas Angular 2 In Memory Web API does workAngular 2 RxJs Promise 不适用于对 C# 控制器的 http.get 调用,而 Angular 2 In Memory Web API 确实有效
【发布时间】:2017-01-11 16:10:48
【问题描述】:

我正在使用 ASP.NET Core 和 Angular 2(版本 ~2.2.0)和 Rxjs(版本 ^5.0.0-rc.5)。 angular.io 文档中的代码示例适用于 Angular 2 的 In Memory Web API,但是当我对 C# 控制器进行 http.get 调用时,它会失败。正在返回数据。以下代码行不起作用:

getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
           .toPromise()
           .then(response => response.json().data as Hero[])
           .catch(this.handleError);
  }

我已经更改了代码,并且以下这些代码行可以正常工作:

getHeroes(): Hero[] {
    this.http.get(this.heroesUrl).map(response => response.json()).subscribe(heroes => {
        this.heroes = heroes;
    })
    return this.heroes;
}

有人可以帮忙吗?我真的需要让第一行代码工作,因为第二行代码没有按计划工作,它们只是证明正在返回和显示数据。

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。请参阅“如何提问”页面以获得澄清此问题的帮助。
  • 为什么你在一个地方使用response.json().data而在另一个地方只使用response.json()?不应该一样吗?
  • 从代码的第二个示例中可以清楚地看出,数据是从 C# 控制器返回并由 Angular 2 显示的。第一个代码示例来自 angular.io 文档,而 Promise 不是在职的。我可能会将 Promise 更改为 Observable 以使其正常工作。我不清楚为什么 Promise 不起作用。

标签: c# asp.net angular typescript rxjs


【解决方案1】:

你可以像这样使用promise

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 2017-03-19
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    相关资源
    最近更新 更多