如何将Promise绑定到组件属性?

时间:2016-01-24 20:20:12

标签: angular

我有一个promise对象需要解析为另一个组件,如何实现这一点,以便在解析component-one中的promise时,解析为component-two的promise对象也可以解析?< / p>

ComponentOne摘录

&#13;
&#13;
@Component({
  selector: 'component-one',
  template: `
      <h1>Title</h1>
      <component-two [promisedData]="promisedData"></component-two>
    `,
  directives: [ComponentTwo]
  })
export class ComponentOne {
  promisedData: Promise<any>;
  
  constructor () {
    this.promisedData = new Promised(resolve => {
             setTimeout(function(){
                 resolve('Test');
              }, 1000);
    });
  }
}
&#13;
&#13;
&#13;

ComponentTwo摘录

&#13;
&#13;
@Component({
  selector: 'component-two',
  template: `
      <h2>
        {{processedData}} 
        // the {{processedData}} is undefined becaused the 
        // resolved promise doesn't get to parse to the component-two.
      </h2>
    `,
  inputs: ['promisedData']
  })
export class ComponentTwo {
  promisedData: Promise<any>;
  processedData: string;
  
  constructor () {
    PromisedData.then(data => this.processedData = data);  
  }
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:8)

简单的方法是将async管道添加到您的模板中,如下所示:

{{promisedData | async}}

编辑:这是一个显示async管道的工作示例:plunker

Edit2:Plunker显示OnInit:plunker

答案 1 :(得分:0)

马克·迈耶的答案是绝对正确的。

但是,如果您承诺的值是一个对象,并且您需要访问它的属性,则可以编写:

  {{ (promissedObject | async).property }}