使用方法而不是构造函数注入服务

Injecting a service using a method instead of the constructor

说我有这个服务和组件。我想使用 MySillyService 的多个实例。

@Injectable()
export class MySillyService {

}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})


export class AppComponent {

  vals: Array<MySillyService>;

  constructor() {

    this.vals = [1,2,3].map(v => {
       return this.getSillyService();
    });

  }

  @Inject(MySillyService)
  getSillyService(mss: MySillyService){
    console.log('getting mss...');
    return mss;
  }

}

这不会编译,因为我得到这个错误:

有没有办法使用方法而不是构造函数来注入服务的新实例?

不,没有。但是你可以通过给它们命名不同的东西来注入多个实例:

构造函数(私有 myService1:数据服务,私有 myService2:数据服务){ }

如果您真的不需要 Angular 的实例管理(单个实例)或其依赖注入,您可以创建一个简单的 class。然后您可以创建并传递您需要的实例数量。

我不认为这是一个常用的技术......但它应该有用。

Injector 服务可用于通过以下方法注入服务:

import { Injector } from '@angular/core';

export class AppComponent {

    vals: Array<MySillyService>;
    mySillyService: MySillyService;

    constructor(private injector: Injector) {
       this.vals = ['some','dynamic','array'].map(v => this.getSillyService());
    }

    getSillyService() {
       return this.injector.get(MySillyService);
    }

    injectAnotherInstance() {
       this.mySillyService = this.injector.get(MySillyService);
    }
}