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

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

问题描述

我正在尝试将字符串注入到我的角度组件中. 下面的代码可以正常工作,但是会给出弃用警告: 不赞成使用:从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.

对于动态组件加载和注入,我需要它.可以在以下位置找到完整的柱塞:柱塞动态组件加载和注入

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

警告是指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(令牌:类型| 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注入器-如何注入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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