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

时间:2019-07-14 17:43:43

标签: angular angular8

@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中说允许引用尚未定义的引用。但是,如果未定义引用,则应引发异常。

1 个答案:

答案 0 :(得分: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
}
相关问题