【问题标题】:Why use Angular forwardRef in component provider?为什么在组件提供者中使用 Angular forwardRef?
【发布时间】:2019-07-14 17:43:43
【问题描述】:
@Component({
  selector: 'my-component',
  template: `<ng-content></ng-content>`,
  providers: [
    { provide: SourceComponent, useExisting: forwardRef(() => TargetComponent) }
  ]
})
export class TargetComponent extends SourceComponent implements OnInit {

}

此组件在装饰器中使用providers 属性。但我无法理解forwardRef() 在这里的目标。在documentation 中说允许引用尚未定义的引用。但是如果没有定义引用,它应该抛出异常。

【问题讨论】:

    标签: angular angular8


    【解决方案1】:

    所以从 forwardRef() 的文档中可以看出。

    允许引用尚未定义的引用。

    它基本上做到了它所说的。它允许您在定义之前引用运行时引用。

    举个例子。

    const x = Example; 
    // throws "Uncaught ReferenceError: Cannot access 'Example' before initialization"
    const Example = "Hello";
    

    上面的变量Example在定义之前就被使用了,这会触发运行时错误。

    我们可以通过使用函数来解决这个问题,因为 JavaScript 在执行时解析范围。

    const x = () => Example;
    const Example = "Hello";
    console.log(x()); // prints "Hello"
    

    上面打印了"Hello",因为JavaScript 在执行时评估函数,并且变量Example 存在于声明函数的堆栈帧中。

    现在查看您的示例,发现 TargetComponent 在声明之前已被引用,但我们通过使用函数避免了错误。

    @Component({
      // ....
      providers: [
        { provide: SourceComponent, useExisting: forwardRef(() => TargetComponent) }
                                                               // ^^ not defined yet
      ]
    })
    export class TargetComponent extends SourceComponent implements OnInit {
              // ^^ declared here lower in source code
    }
    

    【讨论】:

    • 我还会查看转译的代码,我们可以看到 TargetComponent 是在装饰器之前定义的。 typescriptlang.org/play/index.html#code/…
    • 很好的解释,还有一个问题,为什么需要 forwardRef 函数?为什么这个useExisting: () =&gt; TargetComponent 还不够?
    • @robert Angular 对 forwardRef 进行了特殊处理,它只会解压缩包裹在 forwardRef github.com/angular/angular/blob/… 中的箭头函数。
    • 如果我把providers 删掉有什么问题吗?
    猜你喜欢
    • 2021-05-29
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多