簡體   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