【问题标题】:What is the purpose of ApplicationRef in Angular 2+?Angular 2+ 中 ApplicationRef 的目的是什么?
【发布时间】:2017-06-16 07:31:21
【问题描述】:

我不明白ApplicationRef 类及其用途。有一个“reference to an Angular application running on a page”是什么意思?什么时候需要?

请提供一个使用ApplicationRef的小例子。

【问题讨论】:

    标签: angular


    【解决方案1】:

    https://angular.io/api/core/ApplicationRef

    • 允许通过调用appRef.tick() 来调用应用程序范围的更改检测
    • 它允许使用attachView()detachView() 添加/删除要包含在更改检测中或从更改检测中排除的视图
    • 使用componentTypescomponents 提供已注册组件和组件类型的列表 以及其他一些变更检测相关信息

    【讨论】:

      【解决方案2】:

      ApplicationRef 包含对根视图的引用,可用于使用tick 函数手动运行更改检测

      调用此方法以显式处理更改检测及其 副作用。

      在开发模式下,tick() 还会执行第二次更改检测 循环以确保没有检测到进一步的变化。如果额外 在第二个周期中获取更改,应用程序中的绑定 具有无法在单个更改检测中解决的副作用 经过。在这种情况下,Angular 会抛出一个错误,因为 Angular 应用程序只能有一个更改检测通过,在此期间所有 必须完成变更检测。

      这是一个例子:

      @Component()
      class C {
         property = 3;
         constructor(app: ApplicationRef, zone: NgZone) {
             // this emulates any third party code that runs outside Angular zone
             zone.runOutsideAngular(()=>{
                setTimeout(()=>{
                   // this won't be reflected in the component view
                   this.property = 5;
      
                   // but if you run detection manually you will see the changes
                   app.tick();
                })
             })
      

      如果它是使用根节点创建的,另一个应用程序是附加一个动态创建的组件视图以进行更改检测:

        addDynamicComponent() {
           let factory = this.resolver.resolveComponentFactory(SimpleComponent);
      
           let newNode = document.createElement('div');
           newNode.id = 'placeholder';
           document.getElementById('container').appendChild(newNode);
      
           const ref = factory.create(this.injector, [], newNode);
           this.app.attachView(ref.hostView);
        }
      

      查看this answer了解更多详情。

      【讨论】:

      • 我建议添加一些关于注册组件 API 的详细信息,这绝对是最好的答案:)
      猜你喜欢
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 2017-02-09
      • 2017-08-16
      • 2016-01-17
      • 2016-11-02
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多