2016-09-22 66 views
0

我有一個視圖,調用下面這個函數使得我們的API的AJAX調用 - 由於某種原因,當我在AngularScope中使用AngularScope時,總是返回'undefined' Firefox DOM檢測工具。如何從AJAX調用(AngularJS)正確地返回我的數據

如果我檢查網絡標籤,我可以看到這個URL已被調用,並可以看到我期待的JSON,然後我想返回data.words JSON數據,但是這總是返回undefined?如果我刪除了AJAX調用,並且在最後一次返回時使用了「靜態」和「單詞」,這在我看來很有效,所以我很清楚AJAX成功調用的返回似乎並不正確... 有任何想法嗎??

//內的AngularJS服務文件

this.getAccSignoffWords = function() { 
    var url = ApiService.getDomain() + 'account/signoff'; 
    $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      return data.words; // I want to return this JSON to the scope 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 

    // return [ 'static', 'words' ]; // this line is commented out and only used for testing and is an example of the type of data expected from data.words 
} 
+0

這個函數嘗試解析在成功調用數據傳回:'數據= JSON.parse(數據)' –

+0

嗨Nishanth,其中這應該放在 - 我要刪除成功塊內的當前返回 – Zabs

+0

嗯仍然沒有喜悅使用,在成功塊.. :( – Zabs

回答

1

事情是當你發送http請求,它需要一些時間來處理和發送數據回你的JavaScript代碼。但由於JavaScript是異步的,它不會等到響應返回。所以要麼你可以返回整個http請求,如Umakanta Behera建議,或者你可以使用回調函數等待單元的響應回來。

this.getAccSignoffWords = function(callback) { 
    var url = ApiService.getDomain() + 'account/signoff'; 
    $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      callback() data.words 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 
} 

呼叫這樣

this.getAccSignoffWords(function(data){ 
    console.log(data) // your http response 
}) 
+0

你可以指出第二個'調用'函數與我的代碼相關的地方(是這個控制器,服務,視圖等)。謝謝 – Zabs

+1

從你的控制器調用它 –

1

,如果你想將其分配到的範圍,你應該做的那是因爲你的AJAX不返回任何東西..:

var self = this; 
var url = ApiService.getDomain() + 'account/signoff'; 
    $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      self.getAccSignoffWords = data.words; // I want to return this JSON to the scope 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 
0

我認爲你沒有重新調整$ http結果。請你嘗試下面的代碼。

this.getAccSignoffWords = function() { 
    var url = ApiService.getDomain() + 'account/signoff'; 
    return $http({ 
     method : 'GET', 
     url : url 
    }).success(function(data) { 
     if (data.success) { 
      return data.words; // I want to return this JSON to the scope 
     } 
    }).error(function(data) { 
     throw "Failed to get sign-off words"; 
    })['finally'](function(data) { 

    }); 

    // return [ 'static', 'words' ]; // this line is commented out and only used for testing and is an example of the type of data expected from data.words 
} 
+0

感謝烏瑪卡坦,雖然這給了我同樣的問題,雖然 – Zabs

+0

它是否適用於你? –

+0

似乎並不爲我工作我正在做一些傻事我很確定,我會繼續:) – Zabs

相關問題