在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物件?求解!謝謝!
黄舟2017-05-15 17:16:26
首先我這邊用的是ng1+ts,需要注意先註入$q
private $q: ng.IQService
angular.module("app").controller("$q",demoController]);
var deferred = this.$q.defer();
if (!this.clientId || !this.$scope.goodsTypeId) {
// deferred.resolve("well done!");
} else {
return this.goodsService.getList(this.clientId, value, this.$scope.goodsTypeId, 0, 5).then(res => {
return res.data.list;
})
}
return deferred.promise;
我找到更好的方法