Shr*_*i B 5 service dependency-injection autowired 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[];
}
Run Code Online (Sandbox Code Playgroud)
然后,以下是实现抽象类服务的两个服务: 第一个服务:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
第二项服务:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在我的组件中,单击按钮后,我需要决定需要注入哪个服务,并相应地执行“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);
}
}
Run Code Online (Sandbox Code Playgroud)
每次单击按钮时,我需要一种方法来更新提供程序数组或仅更新“useClass”属性。
简而言之,有一个抽象类 BaseService 和“NovelService”和“ReferenceBookService”作为它们的实现,我如何动态地决定将它们中的哪一个注入到我的组件中?
如果您用于providedIn: 'root'您的服务,那么 Injector 肯定有它们,您可以简单地使用get它们:
constructor(private injector: Injector) {}
...
this.myService = this.injector.get(MyService);
Run Code Online (Sandbox Code Playgroud)
然后你就不需要注入baseClass了。也@Injectable从中删除
| 归档时间: |
|
| 查看次数: |
261 次 |
| 最近记录: |