Roy*_*med 3 dependency-injection angular angular5
我正在尝试将字符串注入我的角度组件.下面的代码工作正常,但它给出了弃用警告: 不推荐使用get:从v4.0.0开始使用Type或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');
}
}
Run Code Online (Sandbox Code Playgroud)
因此我尝试使用这个非常简短
且不完整的文档Angular 5 Injector来提出类似下面的内容,但是我不想useValue或者useClass,我需要的是注入的实际值.
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
Run Code Online (Sandbox Code Playgroud)
我真的被困在这里,文档根本没有帮助.
我需要这个动态组件加载和注入.Full Plunker可在以下位置找到:Plunker Dynamic Component Loading and Injection
get 已弃用:从 v4.0.0 开始使用 Type 或 InjectionToken
警告指的injector.get是泛型方法并需要类型参数的事实。这正是Injector文档所说的:
get(token: Type | InjectionToken, notFoundValue?: T): T
考虑到name字符串令牌应该解析为字符串,它应该是:
this.injector.get<string>(<any>'name');
Run Code Online (Sandbox Code Playgroud)
字符串令牌也已弃用,并且令牌应该是函数或InjectionToken实例。
但是我不想 useValue 或 useClass,我需要的是注入的实际值。
所有依赖项都应注册为模块或组件提供程序以便注入。
首先你需要创建一个InjectionToken(这里values.ts):
import { InjectionToken } from '@angular/core';
export const PAGE_TITLE = new InjectionToken<string>('page.title');
Run Code Online (Sandbox Code Playgroud)
然后,您需要将其导入模块并在请求该令牌时提供值:
providers: [ HeroService, MessageService,
{ provide: PAGE_TITLE, useValue: "My Wonderful Title" }
],
Run Code Online (Sandbox Code Playgroud)
然后,您需要将该标记导入要注入值的标记并使用@Inject():
constructor(@Inject(PAGE_TITLE) title) {
this.title = title;
}
Run Code Online (Sandbox Code Playgroud)
看着ReflectiveInjector它说它很慢而且用Injector.createbtw代替...
| 归档时间: |
|
| 查看次数: |
5457 次 |
| 最近记录: |