Angular2 @Input来自异步管道-ngOnInit中的可用性 [英] Angular2 @Input from async pipe - availability in ngOnInit

查看:215
本文介绍了Angular2 @Input来自异步管道-ngOnInit中的可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个博客上,我读到了:

On one blog I've read that:

ngOnInit生命周期挂钩可确保您的绑定是 随时可用.

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>

在启动ngOnInit之前,组件将等待变量解析吗?

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.

推荐答案

简短的回答是否",组件实例化不会延迟,并且如果可观察到的避难所,您不会在onInit 中获得解析值.在第一个变更检测周期之前尚未解决.

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.

比较以下内容:

  // 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>

这是使用async管道时在幕后发生的事情:

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

async管道具有方法transform,该方法在每个更改检测周期均被调用.此方法负责返回将向下传递给子组件的可观察对象的当前解析值.如果在第一个更改检测周期之前未解决可观察项,则子组件将在onInit中获得null.

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.

然后,在下一个摘要循环中,您的绑定将更新,因为transform将返回已解析的值.有趣的是,可观察对象的分辨率可以触发更改检测周期.您可以在onChanges生命周期挂钩中获取绑定的新值.

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.

这篇关于Angular2 @Input来自异步管道-ngOnInit中的可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆