Angular 6. 是否可以按条件注入服务? [英] Angular 6. Is it possible to inject service by condition?

查看:19
本文介绍了Angular 6. 是否可以按条件注入服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的角度应用程序(带有角度材料)中,我有一个过滤器面板,除了选择之外,我还希望能够进行自动完成(用户输入值并将其发送到后端,通过 $regexp 查询我们找到匹配项在 MongoDB 集合中).但要做到这一点,我需要手动将服务注入过滤器组件.我没有找到任何有关如何操作的信息.

我需要这样的东西:

if (filters.serviceName) {注入器.注入(服务名称);}注入器.get(serviceName).find(searchQuery);

有可能吗?谢谢.

解决方案

是的,您可以使用 injector.get()

示例代码:

import { Component, Injector } from '@angular/core';从 './my.service' 导入 { MyService };@成分({选择器:'我的应用',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {name = '角度';我的服务:我的服务;构造函数(私有注入器:注入器){if(true){//一些条件this.myService = injector.get(MyService);}控制台日志(this.myService.prop1)}}

工作 演示

In my angular app (with the angular material) I have a filter panel and I want besides select to be able to make autocomplete (user input value and it sends to the back-end, whereby $regexp query we find the match in MongoDB collection). But to do it I need manually inject service into filters component. I didn't find any info on how to do it.

I need something like this:

if (filters.serviceName) {
  injector.inject(serviceName);
}

injector.get(serviceName).find(searchQuery);

Is it possible? Thanks.

解决方案

Yes you can inject service dynamically using injector.get()

Sample code :

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

这篇关于Angular 6. 是否可以按条件注入服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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