为什么在组件提供者中使用 Angular forwardRef?

Why use Angular forwardRef in component provider?

@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 中表示允许引用尚未定义的引用。但是如果一个引用没有定义它应该抛出异常。

forwardRef() 的文档中说。

Allows to refer to references which are not yet defined.

它基本上做到了它所说的。它允许您在定义之前引用 run-time 引用。

举个例子

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

上面的变量Example在定义之前被使用,这会触发run-time错误。

我们可以使用一个函数来解决这个问题,因为 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
}