我创建了一个抽象类,作为其他两个服务的基础服务。以下是这个抽象类的代码片段:
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[];
}
接下来是实现抽象类service的两个服务: 第一个服务:
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);
}
}
每次点击按钮时,我需要一种更新providers数组或只更新"useClass"属性的方法。
简而言之,有一个抽象类BaseService和"NovelService"和"ReferenceBookService"作为它们的实现,我如何动态决定在我的组件中注入哪个服务?