gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:00:13 26 4
gpt4 key购买 nike

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

最佳答案

因此来自 forwardRef() 的文档它说。

Allows to refer to references which are not yet defined.

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

以下面的例子为例。

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
}

关于angular - 为什么在组件提供者中使用 Angular forwardRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com