在指令中手动从注入器获取依赖
Getting dependency from Injector manually inside a directive
我正在尝试创建一个通用指令,它将采用类类型进行规则验证,并根据类中的规则,该指令将显示或隐藏元素。
这是我目前为止的尝试。
恰好演示
myIf-Directive.ts
@Directive({
selector: '[myIf]'
})
export class MyIfDirective {
constructor(private _viewContainer: ViewContainerRef,
private _template: TemplateRef<Object>)
{ }
@Input() set myIf(rule: string) {
//rule class type will come as string
//how can I use string token to get dependency from injector?
//currently harcoded
//will the injector create new instance or pass on instance from parent?
let injector = ReflectiveInjector.resolveAndCreate([AdminOnly]);
let adminOnly : IRule = injector.get(AdminOnly);
let show = adminOnly.shouldShowElement();
show ? this.showItem() : this.hideItem();
}
private showItem() {
this._viewContainer.createEmbeddedView(this._template);
}
private hideItem() {
this._viewContainer.clear();
}
}
app-component.ts
@Component({
selector: 'my-app',
template: `
<div *myIf="'AdminOnly'">
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
但我被困在两个地方:
- 我一直得到错误
No Provider for AuthService
- 我不知道如何从注入器获得依赖使用类名作为字符串而不是类型
任何建议是否这是正确的方式去做,或者我错了,是非常感谢。
你需要像
这样传递父注入器export class MyIfDirective {
constructor(private injector:Injector, private _viewContainer: ViewContainerRef,
private _template: TemplateRef<Object>)
{ }
@Input() set myIf(rule: string) {
let resolvedProviders = ReflectiveInjector.resolve([AdminOnly]);
let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);
let adminOnly : IRule = childInjector.get(AdminOnly);
let show = adminOnly.shouldShowElement();
show ? this.showItem() : this.hideItem();
}
private showItem() {
this._viewContainer.createEmbeddedView(this._template);
}
private hideItem() {
this._viewContainer.clear();
}
}
参见用ReflectiveInjector注入服务,而不指定依赖树中的所有类
只需更新Angular 10+版本:
- 从您的服务:
@Injectable({
providedIn: 'any'
})
export class AdminOnly { ... }
- 在指令或纯函数中,…:
import { Injector } from '@angular/core';
...
const injector: Injector = Injector.create({
providers: [{provide: AdminOnly, deps: []}]
});
const adminOnly: AdminOnly = injector.get(AdminOnly);
let show = adminOnly.shouldShowElement();
...
看到更多
相关文章:
- 使用javascript和css选择器获取value属性的内容
- 通过CK编辑器获取值和存储数据
- AngularJS 服务注入器错误
- 在运行时从Angular注入器检索实例
- 最小化httpInterceptor AngularJS$注入器错误
- 如何从Bootstrap日期时间选择器获取原始日期数据
- 对话框,数据选择器获取id
- 如何通过元素选择器获取tinyMCE编辑器实例
- jQuery data():can't使用jQuery选择器获取存储的数据
- 从钛合金中的选取器获取所选行
- Phonegap:解析从本机文件选择器获取 content:// URI
- 通过雅虎地方查找器获取JSON数据
- Javascript 单击侦听器获取类
- 如何从角度王牌编辑器获取修改后的文本
- 角度 UI 日期选择器获取错误的日期
- 光谱颜色选取器获取颜色的值
- 从日期选取器获取输出
- AngularJS:骨架应用程序上的注入器模块rr错误
- 通过注入器获取url参数查询
- 在指令中手动从注入器获取依赖