angular - 为什么在组件提供者中使用 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()
这里的目的。在文档中说允许引用尚未定义的引用。但是如果没有定义引用,它应该抛出异常。
解决方案
因此,从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
}
推荐阅读
- laravel - 当我登录到 Laravel Stack Channel 时,信息在哪里?
- pdf - PDF命名字典修改
- python - 为什么在 Python 3.6 中通过 TCP 套接字发送列表时我的输出会有所不同?
- gradle - Gradle 的简写形式 dependsOn, mustRunAfter
- javascript - 从html调用的用于图像旋转的slider.js同时旋转所有图像而不是旋转
- c++ - 无法遍历 std::map
- django - 具有相同两个类的多个多对多关系 - Django
- c++ - 指针数组交换,无需直接访问数组
- python - 将 Pandas pivot_table 子绘制到 matplotlib 图形中会创建一个新图形
- java - 在 Android 上构建 ZIP 文件