角2 - 显示从承诺异步数据对象 [英] Angular 2 - Displaying async Object data from 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]
问题是,我想能够显示各种不同的属性;即,名称,符号等。在角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承诺,不存在。我想,以解决数据的承诺,然后显示,从它的名字关键。目前,我正在创造我自己管显示来自一个异步目的的关键,但我不知道是否有一个内置的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!
我已经创建了一个包含返回一个对象,以我StockInfo类,其中包含要显示的HTML一个承诺一个StockService类。我想显示此对象我的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:
<h2>{{name | async}}</h2>
我已经尝试了一些不同的安排,解决在这一个之前。我想StockService类来处理数据的抓取和StockInfo类来处理画面。在角1,我愿意为获取数据创建一个工厂,并在控制器处理数据的处理,但我不太清楚如何去了解这角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.
有没有办法让它显示,还是有更好的方法来设计我的code,我应该考虑?谢谢!
Is there a way to get it to display, or are there better ways to design my code that I should look into? Thanks!
推荐答案
所以,我结束了写我自己的异步关键管道。巨大的感谢西蒙帮助引导我在这里。
So I ended up writing my own asynchronous key pipe. Huge thanks to Simon for helping guide me here.
import {Pipe} from 'angular2/core';
@Pipe({
name: 'key',
pure: false
})
export class KeyPipe {
private fetchedPromise: Promise<Object>;
private result: string;
transform(value: Promise<Object>, args: string[]) {
if(!this.fetchedPromise) {
this.fetchedPromise = value
.then((obj) => this.result = obj[args[0]] );
}
return this.result;
}
}
用法:
<h2>{{ data | key: 'Name' }}</h2>
有人请评论,如果角都有自己的功能,解决因异步目标的关键。
Someone please comment if Angular has its own functions for resolving a key from an asynchronous object.
这篇关于角2 - 显示从承诺异步数据对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!