将特定的子服务注入组件相当简单,但如何注入另一个服务?
示例:父服务
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export abstract class ParentService {
constructor() { }
abstract testMe(): void;
}
儿童服务
import { ParentService } from "./parent.service";
export class ChildService implements ParentService {
testMe(): void {
console.log('child service');
}
}
成分注入
import { Component } from '@angular/core';
import { ChildService } from './services/child.service';
import { ParentService } from './services/parent.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [
{
provide: ParentService,
useClass: ChildService
}
]
})
export class AppComponent {
title = 'angular_poc';
constructor(private service: ParentService) {
this.service.testMe();
}
}
子服务方法是执行的,所以这很好,但如何在新服务而不是组件中执行同样的操作?
import { Injectable } from '@angular/core';
import { ParentService } from './parent.service';
@Injectable({
providedIn: 'root'
})
export class TestService {
constructor(private service: ParentService) { }
run(){
this.service.testMe();
}
}
可注入中没有提供商
我最终选择了将哪个子服务注入组件本身——组件提供程序。
import { Component } from '@angular/core';
import { ChildService } from './services/child.service';
import { ParentService } from './services/parent.service';
import { TestService } from './services/test.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [
TestService,
{
provide: ParentService,
useClass: ChildService
}
]
})
export class AppComponent {
title = 'angular_poc';
constructor(private service: TestService) {
this.service.run();
}
}