http服务端结果异步返回的处理
在configService服务中定义http开发函数
configUrl = 'assets/config.json';
getConfig() {
return this.http.get(this.configUrl);
}
在目标js引入对应服务后,使用this.configService.getConfig().subscribe((res)=>{…})访问结果
showConfig() {
this.configService.getConfig()
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
}
上面两段为官方文档中http的简单用法,在showConfig中,访问封装服务中的getConfig,可以看到,对于界面的赋值在showConfig中直接完成。
有时,我们希望在另一个函数中完成赋值,而不是在showConfig中,此时我们可以使用promise包裹showConfig,使用resolve返回结果。
showConfig() {
return new Promise((resolve)=>{
this.configService.getConfig()
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
resolve(data);
})
}
在另一个函数/赋值函数中,使用then的方式,将值赋给对应变量。
this.showConfig().then((res) => {...});
注:如一项服务中引入使用的其他的服务,则其需要在module.ts中进行providers注册
包括引入使用了http的服务。