2017-07-27 49 views
0

我想將我的服務的輸出返回到控制器的調用變量「響應」。該服務確實被調用,它也有一個輸出,但它永遠不會再回到我的調用。我在這裏做錯了什麼?沒有從AngularJS服務獲得返回值

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); 
+0

可能的[這]一式兩份(https://stackoverflow.com/questions/14220321/how-do-i-return-the-response - 從異步調用),但我真的不確定什麼「它永遠不會再回到我的調用」意味着或如何確定發生(因爲沒有跡象表明'響應'變量被檢查)。 – Quentin

+0

抱歉不清楚你的意思? – ShK

+0

這使我們兩個人。 – Quentin

回答

0

contentType是wrong.Change像這樣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); 

您可以使用。然後在其上解決了這個承諾讓你的API調用返回的細節。

response.then(function(result){ 
    console.log(result.data); 
}) 
+0

爲什麼downvote? :/ – Vivz

0
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 responseData ; 
    CandidateService.AssociatetoJob1(appInfom).then(function(res‌​ponse){ 
    responseData = response.data ; 
    }) 
0

在你的「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); 

的服務也就是剛剛從你的服務電話中刪除。於是()回調,並呼籲「this.AssociatetoJob1」 M ethod像

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

希望它幫助你...