【发布时间】:2017-05-11 15:53:37
【问题描述】:
我是 Angular 2 的新手。我的应用程序有一个配置文件,其中列出了所有 api url。
我创建了一个定位器服务来加载 config.json。其他服务使用此服务来获取其特定的 url。
@Injectable()
export class LocatorService {
private config: any;
private loadConfig: Promise<any>;
constructor(private _http: Http) {
this.loadConfig = this._http.get('config/config.json')
.map(res => this.config = res.json()).toPromise();
}
public getConfig() {
return this.loadConfig.then(() => this.config);
}
}
我有这个向 url 发送 http 请求的其他服务。此服务从定位器服务获取 url。
@Injectable()
export class OtherService {
private _data: any;
private url: string;
constructor(private _http: Http, private locatorService: LocatorService) {
this.geturl();
}
public loadData(): model[] {
this.geturl().then(() => this._http.get()
.map(res => this._data = res.json())
.catch(error =>
Observable.throw(error.json().error || 'Server error'))
.subscribe(t => this._data = t.json());
return this._data;
}
private geturl() {
return this.locatorService.getConfig().then(t => {
this.url = t.serviceUrl;
console.log(this.url);
});
}
}
我的组件调用这个 loadData n 获取所需的数据。我如何达到同样的效果?
我不是很清楚如何等待配置 url 被加载然后发送 http 请求并返回数据。
请帮忙。
【问题讨论】:
-
在这里使用 Promise 有什么意义?这两个请求实际上都是可观察的。你做错了什么,因为上面的代码应该导致顺序请求。请提供MCVE 以复制问题,请提供帮助。
标签: angular promise rxjs observable