http/AJAX 服务端结果异步返回的封装处理

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的服务。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值