【发布时间】:2016-11-17 16:06:57
【问题描述】:
假设我有一个获取属性列表的服务:
export class PropertyService {
private properties: any;
constructor(@Inject(Http) http) {
this.http.get('/properties.json')
.map((res:Response) => res.json())
.subscribe(
data => this.properties = data
);
}
getProperty(property: string) {
this.properties[property];
}
}
问题是properties 在调用getProperty 时尚未加载。
如何让getProperty 等待订阅填充数组?
我宁愿不返回对组件的订阅。
编辑:
我尝试了 paulpdaniels 的回答并与pluck 合作。但我很快就卡住了。
所以基本上我有这个 PropertyService,它返回一个HOST。
我有一个 ApiService,它使用该主机进行另一个 ajax 调用以获取数据。
export class PropertyService {
private properties: any;
constructor(@Inject(Http) http) {
this.properties = http.get('/properties.json')
.map((res:Response) => res.json()).cache(1);
}
getProperty(property: string) {
this.properties.pluck(property);
}
}
export class ApiService {
private http: Http;
private host: string;
constructor(@Inject(Http) http, @Inject(PropertyService) propertyService) {
this.http = http;
this.host = propertyServiceService.getProperty("API.URL"); //Is a subscription
}
getData(): any {
//Here I must subscribe to host, and once available,
//use host to do an ajax call that returns another Observable for the component
}
}
如何实现这一点?
【问题讨论】:
标签: asynchronous typescript angular undefined rxjs