How to bind a Promise to a component property?

2020-07-06 04:00发布

问题:

I have a promise object needs to be parsed to another component, how to achieve this so that when the promise in component-one is resolved, the promise object parsed to component-two can also be resolved?

ComponentOne excerpt

@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);
    });
  }
}

ComponentTwo excerpt

@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);  
  }
}

回答1:

The easy way is to just add the async pipe to your template like this:

{{promisedData | async}}

Edit: here's a working example showing the async pipe: plunker

Edit2: Plunker showing OnInit: plunker



回答2:

The answer of Mark Meyer is absolutely correct.

However, If your promised value is an object, and you need to access a property of it, you can write:

  {{ (promissedObject | async).property }}


标签: angular