11

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);  
  }
}
Jonathan
  • 2,225
  • 4
  • 20
  • 37
Downhillski
  • 2,381
  • 2
  • 25
  • 37

2 Answers2

9

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

Mark
  • 84,957
  • 6
  • 91
  • 136
  • I adjusted the code above, please take another look, I have issue when the promisedData gets resolved in `component-one`, the one in `component-two` doesn't get to sync. – Downhillski Jan 24 '16 at 22:10
  • How to use the promisedData in the constructor? I added something to the constructor -- http://plnkr.co/edit/po34BB8Ff2DysWevc6XO?p=preview – Downhillski Jan 24 '16 at 22:22
  • You can't use it in the constructor. The `@Input` hasn't been parsed yet. Use OnInit. See added plunker and read: http://learnangular2.com/lifecycle/ – Mark Jan 24 '16 at 22:38
  • That's what I am missing! Thank you! – Downhillski Jan 24 '16 at 22:48
0

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 }}
Muhammad Altabba
  • 2,468
  • 14
  • 31