简体   繁体   English

.then没有定义?

[英].then is not defined?

I'm getting this error, when trying to get response from my service, in which i have placed my Ajax call! 尝试从我的Ajax呼叫服务中获取响应时,出现此错误! I want the controller code to delay that is why i am returning a promise from service. 我希望控制器代码延迟,这就是为什么我要从服务中返回承诺。 But I am getting .then of undefined error. 但是我得到.then of undefined错误。
Here is the code 下面是代码

app.service('abc', function(){

    var function() {

        return $http({method : "POST",
                            url :"url",
                            data:{
                                a}
        }).then(function mySuccess(response) {        
                 return response;
        })
    }
});    

in controller 在控制器中

var promise=servicename.functionname();

promise.then(res)
{} 

.then of undefined is the error I am getting. .then undefined是我得到的错误。 Any solution? 有什么办法吗?

Update service and inject $http 更新服务并注入$ http

app.service('abc', function ($http) {
    this.functionName = function (data) {
        return $http({
            method: "POST",
            url: "url",
            data: data
        }).then(function mySuccess(response) {
            return response.data;
        })
    };
});

Controller 控制者

app.controller('myController', function (abc) {
    abc.functionName({
        a: 'a'
    }).then((data) => console.log(data))
});

Here the code will not wait the return inside then() and it will execute the code ahead. 在这里,代码将不等待then()内部的返回,而是将在前面执行代码。 And as it does no find any return statement it will return undefined. 由于找不到任何return语句,因此它将返回undefined。 To fix this in the service function you will return just the promise so your return statement will look something like this 要在服务函数中解决此问题,您将仅返回promise,因此您的return语句将如下所示

return $http({
           method : "POST",
           url :"url",
           data:{a}
   })

The controller code will be same 控制器代码将相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM