forwardRef 在 angular 中有什么作用? [英] what does do forwardRef in angular?

查看:23
本文介绍了forwardRef 在 angular 中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

forwardRef 在 angular 中有什么作用,它的用途是什么?

What does forwardRef do in angular, and what is its usage?

这是一个示例:

import {Component, Injectable, forwardRef} from '@angular/core';

export class ClassCL { value; }

@Component({
    selector: 'my-app',
    template: '<h1>{{ text }}</h1>',
    providers: [{provide: ClassCL, useClass: forwardRef(() => ForwardRefS)}]
})
export class AppComponent {
    text;

    constructor( myClass: ClassCL ) {
        this.text = myClass.value;
    }
}

Injectable()
export class ForwardRefS { value = 'forwardRef works!' }

推荐答案

来自 Angular's API docs on forwardRef:

允许引用尚未定义的引用.

Allows to refer to references which are not yet defined.

例如,forwardRef 用于当我们需要引用的令牌时DI 的目的已声明,但尚未定义.它也用于我们在创建查询时使用的令牌尚未定义.

For instance, forwardRef is used when the token which we need to refer to for the purposes of DI is declared, but not yet defined. It is also used when the token which we use when creating a query is not yet defined.

有一个很好的写在角度深度.

这是一个摘录:

为什么 forwardRef 起作用?

现在您的脑海中可能会出现forwardRef 是如何工作的问题.它实际上与 JavaScript 中的闭包如何工作有关.当你在闭包函数中捕获一个变量时,它捕获的是变量引用,而不是变量值.下面是一个小例子来证明这一点:

Now the question may pop up in your head how the forwardRef works. It actually has to do with how closures in JavaScript work. When you capture a variable inside a closure function it captures the variable reference, not the variable value. Here is the small example to demonstrate that:

let a;
function enclose() {
    console.log(a);
}

enclose(); // undefined

a = 5;
enclose(); // 5

您可以看到,尽管在创建 enclose 函数时变量 a 未定义,但它捕获了变量引用.因此,当稍后将变量更新为 5 时,它记录了正确的值.

You can see that although the variable a was undefined at the moment the enclose function was created, it captured the variable reference. So when later the variable was updated to the 5 it logged the correct value.

而且 forwardRef 只是一个函数,它捕获一个类引用到闭包中,并且类在函数执行之前被定义.Angular 编译器使用函数 resolveForward> 在运行时解开令牌或提供程序类型.

And forwardRef is just a function that captures a class reference into closure and class becomes defined before the function is executed. Angular compiler uses the function resolveForwardRef to unwrap the token or provider type during runtime.

这篇关于forwardRef 在 angular 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆