繁体   English   中英

无法从AngularJS的Service中获取返回值

[英]Not getting return value from Service in AngularJS

我正在尝试将下面我的服务输出返回到控制器的调用变量“ response”。 该服务确实会被调用,它也有一个输出,但是它再也不会回到我的调用了。 我在这里做错了什么?

this.AssociatetoJob1 = function (application) {
    var config = {
        headers: {
            'contentType': 'application/json; charset=utf-8;'
        }
    };
    return $http.post('/api/Application/AddApplication', 
        JSON.stringify(application), config).then(function (result) {
            return result.data;
        });     
}

下面是我调用控制器的那一行:

var response = CandidateService.AssociatetoJob1(appInfom);

您的contentType错误。按此Content-Type更改

JS

    this.AssociatetoJob1 = function (application) {
    var config = {
        headers: {
            'Content-Type': 'application/json; charset=utf-8;'
        }
    }
    return $http.post('/api/Application/AddApplication', JSON.stringify(application), config).then(function (result) {
        return result.data;
    });

}

HTML

var response = CandidateService.AssociatetoJob1(appInfom);

您可以在已解决的承诺上使用.then来获取API调用返回的详细信息。

response.then(function(result){
  console.log(result.data);
})
this.AssociatetoJob1 = function (application) {
    var config = {
        headers: {
            'contentType': 'application/json; charset=utf-8;'
        }
    }
    return $http.post('/api/Application/AddApplication', JSON.stringify(application), config).then(function (result) {
        return result.data;
    });

}

上面的代码确实返回了Promise对象。 为了利用此功能,您需要在控制器中执行以下操作:

  var responseData ; 
  CandidateService.AssociatetoJob1(appInfom).then(function(res‌​ponse){ 
     responseData  = response.data ;
    })

在“ this.AssociatetoJob1”函数中,您将服务称为

return $http.post('/api/Application/AddApplication', JSON.stringify(application), config).then(function (result) {
    return result.data;
});

在这种情况下,您在调用服务时使用了回调函数,而不是像下面这样调用服务

return $http.post('/api/Application/AddApplication', JSON.stringify(application), config);

这意味着只需从服务调用中删除.then()回调,然后调用“ this.AssociatetoJob1”方法即可

this.AssociatetoJob1(application).then(function(response){console.log(response.Data)});

希望它可以帮助您...

暂无
暂无

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

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