我创建了3个Angular2服务,可从不同的http端点检索类别,位置和项目。我现在想创建一个新的服务,从这些服务中检索数据,并从检索到的所有数据创建一个新的DataSet,但我无法从非迭代的DataSet对象创建Observable。非阵列类型可观察
有没有更好的方法来将数据整合到单个结构中,例如使用Observables?
export class DataSet {
items: Item[];
locations: Location[];
categories: Category[];
}
@Injectable()
export class DataService {
_data : DataSet;
constructor(
private _http: Http,
private _categoryService: CategoryService,
private _locationService: LocationService,
private _itemService: ItemService) { }
getDataSet(): DataSet {
this._data = new DataSet();
this._categoryService.getCategories().subscribe(cats => {
this._data.categories = cats;
});
this._locationService.getLocations().subscribe(locs => {
this._data.locations = locs;
});
this._itemService.getItems(null).subscribe(items => {
this._data.items = items;
});
// ERROR can't create observable from non array type dataset
return Observable.from(this._data);
}
}
感谢Aluan,您回答了有关Observable.of的问题,但没有达到预期的结果。我期待的订阅者将不会被调用,直到嵌套集合填充,但我想我需要看看可观察的链接。 – Dennis
这是正确的。您可以使用合并或分叉连接或concat。一切都不一样。 –
当然,在RxJS中也有几十种其他方法可以做到这一点。不幸的是,最明显的方式是用地图调用代替所有的订阅调用,然后嵌套,这将导致代码不可读。 –