我是angularJs中的新成員,我試圖在開發應用程序方面有第一步,而且我正面臨一個問題。angularjs undefined resource
我打電話給一個外部資源,通過$ resource.get()返回一個對象json,在callBack中我得到正確的值,但在服務中值是未定義的,問題是當我打印資源在控制檯中的結果具有正確的值。
我的JSON對象:
{
"readOnly": false,
"questions": [
{
"questionId": "0",
"questionTitle": "question0",
"isMondatory": true,
"responseList": [
{
"questionId": "0",
"questionTitle": null,
"responseId": "00",
"responseTitle": "response00"
},
{
"questionId": "0",
"questionTitle": null,
"responseId": "01",
"responseTitle": "response01"
},
{
"questionId": "0",
"questionTitle": null,
"responseId": "02",
"responseTitle": "response02"
},
{
"questionId": "0",
"questionTitle": null,
"responseId": "03",
"responseTitle": "response03"
}
]
},
{
"questionId": "1",
"questionTitle": "question1",
"isMondatory": true,
"responseList": [
{
"questionId": "1",
"questionTitle": null,
"responseId": "10",
"responseTitle": "response10"
},
{
"questionId": "1",
"questionTitle": null,
"responseId": "11",
"responseTitle": "response11"
},
{
"questionId": "1",
"questionTitle": null,
"responseId": "12",
"responseTitle": "response12"
},
{
"questionId": "1",
"questionTitle": null,
"responseId": "13",
"responseTitle": "response13"
}
]
}
我控制器
app.controller('mycontroller', function ($scope,myservice) {
$scope.infos = null;
$scope.infos = myservice.getInfo();
}
我的服務是:
angular.module('xxxx').factory('myservice', function($window,$resource,$routeParams,$http,apicallservice) {
// Public API here
return {
getInfo : function(){
var result=null;
var url = "myUrl";
result = apicallservice.GetApiCall(url,$routeParams);
console.log(result.readOnly); // print undefined => KO
return result;
},
//.... other functions
我apicallservice:
angular.module('xxxx')
.factory('apicallservice', function ($http,$resource) {
var result;
// Public API here
return {
GetApiCall: function (url,obj) {
// resource
var resource = $resource(url,{param1:obj});
// cal the api
result = resource.get(function(callBack) {
console.log(callBack.readOnly); => print false => OK
return callBack;
}, function(error) {
console.log(error);
return error;
});
return result;
},
PostApiCall : function(url,obj){
result = $http.post(url,obj).then(
function (response) {
console.log(response);
}, function (error) {
console.log(error);
});
}
};
});
請問你能幫我嗎? 在此先感謝。
那麼你對我的問題有一些建議嗎? – anonymouslyGeek
因此,您希望'console.log(..)'在您調用'apicallservice.GetApiCall(..)'後立即顯示正確的值?由於$ resource方法的異步性質,這是不可能的。你可以做的是返回'resource'對象(或$ http.get或$ http.post promises),並在回調函數中初始化該值(並在控制檯中打印)。但是,這打敗了使用$ resource –
console.log()的全部目的不是我的問題,我的問題是在我看來我無法顯示結果 – anonymouslyGeek