Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - Angular2 @Input from async pipe - availability in ngOnInit

On one blog I've read that:

The ngOnInit lifecycle hook is a guarantee that your bindings are readily available.

Is it true also with parameters passed using async pipe? For example:

<myComponent [myInput]="myObservableVariable | async">
 ...
</myComponent>

Will component wait for the variable to be resolved before starting up ngOnInit?

That would mean that sometimes, when data will take a while to resolve, component loading could take a long time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The short answer is no, the component instantiation won't be delayed and you will not get a resolved value in onInit if the observable hasn't been resolved before the first change detection cycle.

Compare the following:

  // the value will be available in onInit
  obs = Observable.from([33]);

  // the value will not be available in onInit (you'll get null)
  obs = new Observable(observer => {
    setTimeout(() => {
      observer.next(33);
    }, 1000);

    setTimeout(() => {
      observer.complete();
    }, 3000);
  });


<child-component [inputproperty]="obs"><child-component>

Here is what happens under the hood when you use async pipe:

async pipe has a method transform which is called on every change detection cycle. this method is responsible for returning the current resolved value of the observable that will be passed down to a child component. If the observable hasn't been resolved before the first change detection cycle, your child component will get null in onInit.

Then, during next digest cycle your binding will be updated as transform will return resolved values. What's interesting is that resolution of an observable can trigger the change detection cycle. You can obtain new values for the bindings in onChanges lifecycle hook.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...