Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a Promise to a component property?

Tags:

angular

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);  
  }
}
like image 235
Downhillski Avatar asked Jan 24 '16 20:01

Downhillski


1 Answers

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

like image 103
Mark Avatar answered Sep 22 '22 03:09

Mark