Krz*_*dan 10 dependency-injection angular
Angular DI Multi Provider机制是否保证某种顺序?
例:
const TOKEN: OpaqueToken = new OpaqueToken('token');
@Injectable()
class MyService (@Inject(TOKEN) deps: any[]) {/* What is order of deps? */}
@NgModule ({
providers: [
{provide: TOKEN, multi: true, useValue: 1},
{provide: TOKEN, multi: true, useValue: 2},
{provide: TOKEN, multi: true, useValue: 3},
MyService
})
class MyModule {}
Run Code Online (Sandbox Code Playgroud)
例如,如果您需要在组件 X 中注入类 A,这依赖于其他类,那么最好的方法是将这些类注入到类 A 中。在组件 X 中,您仍然需要声明所有服务。例如:组件X:
import { Component } from '@angular/core';
import {
CarService, CarService2, CarService3,
EngineService, EngineService2, TiresService
} from './car.services';
Run Code Online (Sandbox Code Playgroud)
汽车服务.ts
import { Injectable } from '@angular/core';
/// Model ///
export class Car {
}
export class Engine {
}
export class Tires {
}
//// Engine services ///
@Injectable()
export class EngineService {
}
@Injectable()
export class EngineService2 {
}
//// Tire services ///
@Injectable()
export class TiresService {
}
/// Car Services ///
@Injectable()
export class CarService {
id = 'C1';
constructor(
protected engineService: EngineService,
protected tiresService: TiresService) { }
}
@Injectable()
export class CarService2 extends CarService {
id = 'C2';
constructor(
protected engineService: EngineService,
protected tiresService: TiresService) {
super(engineService, tiresService);
}
}
@Injectable()
export class CarService3 extends CarService2 {
id = 'C3';
constructor(
protected engineService: EngineService,
protected tiresService: TiresService) {
super(engineService, tiresService);
}
}
Run Code Online (Sandbox Code Playgroud)
https://stackblitz.com/angular/vomexgeqgdj?file=src%2Fapp%2Fcar.services.ts
| 归档时间: |
|
| 查看次数: |
1208 次 |
| 最近记录: |