Angular 2 - 显示来自 promise 的异步对象数据 [英] Angular 2 - Displaying async Object data from promise

查看:18
本文介绍了Angular 2 - 显示来自 promise 的异步对象数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在看来我的主要问题是我似乎无法显示来自对象的异步数据.我有一个包含数据对象的承诺,当我使用

It looks like my main problem now is that I can't seem to display async data from an object. I have a promise containing the data object, and when I use

{{ data | async }}

它会显示

[object Object]

问题是,我希望能够显示所有不同的属性;即名称、符号等.在 Angular 1 中,我只会使用

The issue is, I want to be able to display all the different attributes; i.e, Name, Symbol, etc. In Angular 1, I would just use

{{ data.Name | async }}

但这在这里不起作用,因为异步管道试图解析不存在的 data.Name 承诺.我想解析数据承诺,然后从中显示 Name 键.目前,我正在创建自己的管道来显示来自异步对象的键,但我想知道是否有内置的 Angular 2 管道或函数来处理这个问题!

but that doesn't work here, since the async pipe tries to resolve the data.Name promise, which doesn't exist. I want to resolve the data promise and then display the Name key from it. At the moment, I'm working on creating my own pipe to display a key from an async object, but I'm wondering if there's a built-in Angular 2 pipe or function to handle this!

我创建了一个 StockService 类,该类将包含一个对象的 Promise 返回到我的 StockInfo 类,该类包含要显示的 HTML.我想在 HTML 中显示此对象的名称,但似乎无法显示.

I've created a StockService class that returns a Promise containing an object to my StockInfo class, which contains the HTML to be displayed. I want to display the name of this object in my HTML, but I can't seem to get it to display.

在我的 StockInfo 构造函数中:

In my StockInfo constructor:

this.stock.getStockData(this.ticker, http).then(function(val) {
  this.data = val;

  this.name = new Promise<string>(function(resolve) {
    resolve(this.data.Name);
  });
});

其中 this.stock 是 StockService 对象.

where this.stock is the StockService object.

在我的 HTML 中:

In my HTML:

<h2>{{name | async}}</h2>

我已经尝试了许多不同的安排,然后才确定了这一安排.我想要 StockService 类来处理数据获取和 StockInfo 类来处理显示.在 Angular 1 中,我将创建一个工厂来获取数据并处理控制器中的数据处理,但我不太确定如何在 Angular 2 中进行此操作.

I've tried a number of different arrangements before settling on this one. I want the StockService class to handle the data fetching and the StockInfo class to handle the display. In Angular 1, I would create a factory for fetching data and handle the data processing in the controller, but I'm not quite sure how to go about this in Angular 2.

有没有办法让它显示出来,或者有没有更好的方法来设计我应该研究的代码?谢谢!

Is there a way to get it to display, or are there better ways to design my code that I should look into? Thanks!

推荐答案

您不需要任何特殊的管道.Angular 2 支持可选字段.你只需要添加?在你的对象中

You do not need any special pipe. Angular 2 suppport optional field. You just need to add ? in your object

{{ (data | async)?.name }}

{{(name | async)?}}

这篇关于Angular 2 - 显示来自 promise 的异步对象数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆