Angular 5 Injector - 如何注入字符串 [英] Angular 5 Injector - How to inject string

查看:20
本文介绍了Angular 5 Injector - 如何注入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串注入到我的角度组件中.下面的代码工作正常,但它给出了弃用警告:不推荐使用:从 v4.0.0 开始使用 Type 或 InjectionToken

I am trying to inject strings into my angular component. The code below works fine but it gives a deprecation warning: get is deprecated: from v4.0.0 use Type or InjectionToken

@Component({
  selector: 'app-label',
  templateUrl: './label.component.html',
  styleUrls: ['./label.component.scss']
})
export class LabelComponent {
  public name: string;
  public caption: string;
  constructor(
    private injector: Injector
  ) {
    this.name = this.injector.get('name');
    this.caption = this.injector.get('caption');
  }
}

所以我尝试使用这个非常简短且不完整的文档Angular 5 Injector想出类似下面的东西,但是我不想 useValueuseClass,我需要的是注入的实际值.

So i tried to work with this very short and incomplete documentation Angular 5 Injector to come up with something like below, however I don't want to useValue or useClass, what I need is the actual value injected.

    class BS { }
    // [..]
    const name = new InjectionToken<string>('name');
    const caption = new InjectionToken<string>('caption');
    const injector = ReflectiveInjector.resolveAndCreate([
      { provide: name, useClass: BS},
      { provide: caption, useClass: BS}
    ]);
    this.name = this.injector.get(name);
    this.caption = this.injector.get(caption);
    console.log(this.name); // will be an instance of BS

我真的被困在这里,文档根本没有帮助.

I am really stuck here and the documentation is not helping at all.

我需要这个用于动态组件加载和注入.可以在以下位置找到完整的 Plunker:Plunker 动态组件加载和注入

I need this for Dynamic component Loading and Injection. Full Plunker can be found in: Plunker Dynamic Component Loading and Injection

推荐答案

不推荐使用:从 v4.0.0 开始使用 Type 或 InjectionToken

get is deprecated: from v4.0.0 use Type or InjectionToken

warning 指的是 injector.get 是泛型方法并且需要类型参数的事实.这正是 Injector 文档 所述:

warning refers to the fact that injector.get is generic method and expects type argument. This is exactly what Injector documentation states:

get(token: Type | InjectionToken, notFoundValue?: T): T

get(token: Type | InjectionToken, notFoundValue?: T): T

考虑到 name 字符串令牌应该解析为字符串,它应该是:

Considering that name string token is supposed to resolve to a string, it should be:

this.injector.get<string>(<any>'name');

字符串标记也已弃用,并且标记应该是函数或 InjectionToken 实例.

String tokens are deprecated as well, and a token is expected to be either a function or InjectionToken instance.

但是我不想使用useValue或useClass,我需要的是注入的实际值.

however I don't want to useValue or useClass, what I need is the actual value injected.

所有依赖项都应注册为模块或组件提供者才能注入.

All dependencies should be registered as module or component providers in order to be injected.

这篇关于Angular 5 Injector - 如何注入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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