首页 > 解决方案 > Angular 如何处理多个服务的依赖注入?

问题描述

我创建了一个抽象类,作为我的其他两个服务的基础服务。下面是这个抽象类的代码片段:

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

export interface Book {
  title: string;
  description: string;
  price: number;
} 
@Injectable({
  providedIn: 'root'
})
export abstract class BaseService {

      constructor() { }

      abstract getBooks(): Book[];

}

然后,以下是实现抽象类服务的两个服务: 第一个服务:

export class NovelService implements BaseService {

      constructor() { }
      getBooks() {
            const novels: Book[] = [
                {
                  title: 'War and peace',
                  description: "War and Peace broadly focuses on Napoleon's invasion of Russia in 1812",
                  price: 550
                }
              ];

            return novels;
        }

}

二服务:

export class ReferenceBookService implements BaseService {



constructor() { }
getBooks() {
        const referenceBooks: Book[] = [
            {
              title: 'Spring in Action',
              description: "Spring in Action, Fourth Edition is a hands-on guide to the Spring Framework",
              price: 600
            }
          ];

        return referenceBooks;
    }

}

现在,在我的组件中,单击按钮时,我需要决定需要注入哪个服务,并相应地执行“getBooks()”函数以在 html 中打印列表。

我尝试在提供者数组中使用“useClass”属性,如下所示:

import { Component, OnInit } from '@angular/core';
import { Book, BaseService } from '../../services/base.service';
import { NovelService } from '../../services/novels-service';
import { ReferenceBookService } from '../../services/reference-book-service';
let IS_NOVEL_MODE = true;
export function setValue(somevalue) {
  IS_NOVEL_MODE = somevalue;
}
@Component({
  selector: 'app-book',
  template: `<div *ngFor="let book of books">
  <h3>{{ book.title }}</h3>
  <p>{{ book.description }}</p>
</div>
<button (click)="changeMode()">click me!</button>`,
  styleUrls: ['./book.component.css'],
  providers: [{provide: BaseService, useClass: IS_NOVEL_MODE ? NovelService : ReferenceBookService}]
})
export class BookComponent implements OnInit { 
      books: Book[];
      isNovelMode = false;
        constructor(private _baseService: BaseService) { }

          ngOnInit() { 
            this.books = this._baseService.getBooks();
          }
          changeMode() {
            setValue(!this.isNovelMode);
          }

}

每次单击按钮时,我都需要一种更新提供程序数组或仅更新“useClass”属性的方法。

简而言之,有一个抽象类 BaseService 和“NovelService”和“ReferenceBookService”作为它们的实现,我怎样才能动态地决定它们中的哪一个被注入到我的组件中?

标签: angulardependency-injectionserviceautowired

解决方案


如果你使用providedIn: 'root'你的服务,那么 Injector 肯定有它们,你可以简单地使用get它们:

constructor(private injector: Injector) {}
...
this.myService = this.injector.get(MyService);

然后你不需要注入baseClass。@Injectable也从中删除


推荐阅读