Skip to content

Instantly share code, notes, and snippets.

@chgc
Created June 7, 2017 07:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chgc/ea35f15d8ffc40342b12b4822eb1bd07 to your computer and use it in GitHub Desktop.
Save chgc/ea35f15d8ffc40342b12b4822eb1bd07 to your computer and use it in GitHub Desktop.
providers: 使用 multi 的情境
import {Component, Injector} from '@angular/core';
import {serviceToken} from './app.module';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
service: any[];
constructor(private injector: Injector) {
this.service = <any[]>injector.get(serviceToken);
this.callFunction('service2');
}
callFunction(kind: string) {
const idx = this.service.findIndex(x => x.kind === kind);
if (idx > -1) {
console.log(this.service[idx].log());
}
}
}
import {InjectionToken, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {Service1Service} from './service1.service';
import {Service2Service} from './service2.service';
import {Service3Service} from './service3.service';
export const serviceToken = new InjectionToken('serviceToken');
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [
{provide: serviceToken, useClass: Service1Service, multi: true},
{provide: serviceToken, useClass: Service2Service, multi: true},
{provide: serviceToken, useClass: Service3Service, multi: true},
],
bootstrap: [AppComponent]
})
export class AppModule {
}
import {Injectable} from '@angular/core';
@Injectable()
export class Service1Service {
kind = 'service1';
constructor() {}
log() {
return 'service1';
}
}
import {Injectable} from '@angular/core';
@Injectable()
export class Service2Service {
kind = 'service2';
constructor() {}
log() {
return 'service2';
}
}
import {Injectable} from '@angular/core';
@Injectable()
export class Service3Service {
kind = 'service3';
constructor() {}
log() {
return 'service3';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment