首页 > 解决方案 > 为什么在组件提供者中使用 Angular forwardRef?

问题描述

@Component({
  selector: 'my-component',
  template: `<ng-content></ng-content>`,
  providers: [
    { provide: SourceComponent, useExisting: forwardRef(() => TargetComponent) }
  ]
})
export class TargetComponent extends SourceComponent implements OnInit {

}

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

标签: angularangular8

解决方案


因此,从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
}

推荐阅读