我想将多个DataServices传递给组件构造函数。目前我可以逐个传递它们,但我希望能够以更通用的方式将它们作为数组传递。
export class MainGrid {
constructor(private firstService: FirstDataService, private secondService: SecondDataService) { }
// how to do this instead -> constructor(private services: BaseDataService[] ) { }
ngOnInit() {
this.firstService.getData().then(data => {
// do something with data
});
this.secondService.getData().then(data => {
// do something with data
});
// how to do this instead ->
this.services.map((service) => {
service.getData().then(data => {
// do something with data
}
});
}
}
以下是我对BaseDataService
的看法import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Data} from '../../app/data/data';
export abstract class BaseDataService {
constructor() {}
abstract getData()
}
@Injectable()
export class FirstDataService implements BaseDataService{
constructor(private http: Http) {}
getData() {
return this.http.get('app/resources/data/cars-medium.json')
.toPromise()
.then(res => <Data[]> res.json().data)
.then(data => { return data; });
}
}
@Injectable()
export class SecondDataService implements BaseDataService {
constructor(private http: Http) {}
getData() {
return this.http.get('app/resources/data/cars-medium.json')
.toPromise()
.then(res => <Data[]> res.json().data)
.then(data => {
return {
foo: 'bar'
}
});
}
}
所以我的问题是如何以及在何处将BaseDataService数组传递给MainGrid组件构造函数?