angular - 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”作为它们的实现,我怎样才能动态地决定它们中的哪一个被注入到我的组件中?
解决方案
如果你使用providedIn: 'root'
你的服务,那么 Injector 肯定有它们,你可以简单地使用get
它们:
constructor(private injector: Injector) {}
...
this.myService = this.injector.get(MyService);
然后你不需要注入baseClass。@Injectable
也从中删除
推荐阅读
- javascript - 未捕获(承诺):错误:无法匹配任何路线(Angular8)
- botframework - 由于 QnAMaker 连接问题,Bot 未响应 Bot Framework Emulator 中的消息
- json - 我需要将邮递员请求的正文与另一个网站的 XHR 进行比较
- javascript - 在 JavaScript 中完成第一个递归分支后返回树
- git - 从本地服务器克隆存储库缺少提交
- qt - QML 将键盘导航与多个列表视图同步
- azure - 通过电子邮件发送 Azure Metrics 图表 - 以任何方式
- c# - 检查 db 中的值列表并检索属于日期时间月份属性的项目
- ios - 如何将 FirebaseUI 与多个数据源一起用于 tableview?
- vue.js - 无法显示来自请求 Vuejs 的值