angular.js - Angularjs1.5中如何返回一个空的Promise对象

查看:112
本文介绍了angular.js - Angularjs1.5中如何返回一个空的Promise对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在angular1.5.8中我在调用接口返回数据时,如果请求参数为空或undefined,则return,但是这个return返回的值位空没有.then,就报错了
事例代码:

onGoodsNameAutoComplate = (value: string) => {
        if (!this.clientId || !this.$scope.goodsTypeId) {
            return;//这边返回就是空的,没有.then,则会报错
        };
        return this.goodsService.getList(this.clientId, value, this.$scope.goodsTypeId, 0, 5).then(res => {
            return res.data.list;
        })
    }
    


报错代码:

TypeError: Cannot read property 'then' of undefined
    at T (angucomplete-alt.min.js:2)
    at $ (angucomplete-alt.min.js:2)
    at m.b.onFocusHandler (angucomplete-alt.min.js:2)
    at fn (eval at compile (angular.js:14817), <anonymous>:4:233)
    at b (angular.js:15906)
    at e (angular.js:25885)
    at m.$eval (angular.js:17682)
    at m.$apply (angular.js:17782)
    at HTMLInputElement.<anonymous> (angular.js:25890)
    at HTMLInputElement.dispatch (jquery.min.js:3)

我想在这边:

 if (!this.clientId || !this.$scope.goodsTypeId) {
                return;//这边模拟返回一个空的promise对象,就不会报错了。。。
            };

求问如何模拟一个空的promise对象?求解!谢谢!

解决方案

onGoodsNameAutoComplate = (value: string) => {
  return $q(function (resolve, reject) {
    if (!this.clientId || !this.$scope.goodsTypeId) {
      reject('xxx不能为空')
      return
    }
    this.goodsService.getList(this.clientId, value, this.$scope.goodsTypeId, 0, 5).then(
      res => {
        resolve(res.data.list)
      },
      () => reject('无法获取到正确的数据'))
  }
}

这篇关于angular.js - Angularjs1.5中如何返回一个空的Promise对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆