在我的角度应用程序(带有角度材料)中,我有一个过滤器面板,除了选择之外,我还希望能够自动完成(用户输入值并将其发送到后端,通过 $regexp 查询我们在 MongoDB 集合中找到匹配项)。但要做到这一点,我需要手动将服务注入过滤器组件。我没有找到任何有关如何操作的信息。
我需要这样的东西:
if (filters.serviceName) {
injector.inject(serviceName);
}
injector.get(serviceName).find(searchQuery);
是否可以?谢谢。
是的你可以inject
服务动态使用注射器.get() https://angular.io/api/core/Injector#get
示例代码:
import { Component, Injector } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
myService : MyService;
constructor(private injector : Injector){
if(true){ // some condition
this.myService = injector.get<MyService>(MyService);
}
console.log(this.myService.prop1)
}
}
Working demo https://stackblitz.com/edit/dynamic-service-injection?file=src/app/app.component.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)