2013-02-15 50 views
13

$http.put的成功功能無法訪問其在內部調用的服務的範圍this。我需要更新PUT請求回調中的服務屬性。使用錯誤的「this」範圍的AngularJS服務http成功功能

這是我想要的服務做了削減例如:

var myApp = angular.module('myApp', function($routeProvider) { 
// route provider stuff 
}).service('CatalogueService', function($rootScope, $http) { 
    // create an array as part of my catalogue 
    this.items = []; 

    // make a call to get some data for the catalogue 
    this.add = function(id) { 
     $http.put(
      $rootScope.apiURL, 
      {id:id} 
     ).success(function(data,status,headers,config) { 
      // on success push the data to the catalogue 
      // when I try to access "this" - it treats it as the window 
      this.items.push(data); 
     }).success(function(data,status,headers,config) { 
      alert(data); 
     }); 
    } 
} 

很抱歉,如果有在JS的一些錯誤,主要的一點是怎樣訪問服務範圍從成功回調裏面?

編輯:而這個問題的答案是正確的,我切換到factory方法既Josh和馬克推薦它

回答

15

創建了一個變量(通常稱爲that)封閉分配給this讓你的回調函數將有你的服務對象訪問:

app.service('CatalogueService', function($rootScope, $http) { 
    var that = this; 
    ... 
     ).success(function(data,status,headers,config) { 
      that.items.push(data); 

下面是一個使用$超時而不是Plunker $ http來演示。

+4

在這種情況下,我仍然更喜歡工廠方法,但實際上回答問題時使用+1。 :-) – 2013-02-16 18:41:37

+0

@Josh,我更喜歡這個工廠。 – 2013-02-16 18:42:23

+0

我打算拿出工廠的答案,但我覺得我應該選擇這個作爲正確答案,因爲它回答了問題。我肯定會對我的問題添加編輯,提及我已經訴諸了你的問題@JoshDavidMiller – 2013-02-17 21:59:26

23

據我所知,你不能。但我不會試圖以這種方式運行服務。這裏是一個更清潔的方式:

.factory('CatalogueService', function($rootScope, $http) { 
    // We first define a private API for our service. 

    // Private vars. 
    var items = []; 

    // Private methods. 
    function add(id) { 
    $http.put($rootScope.apiURL, {id:id}) 
    .success(function(data,status,headers,config) { items.push(data); }) 
    .then(function(response) { console.log(response.data); }); 
    } 

    function store(obj) { 
    // do stuff 
    } 

    function remove(obj) { 
    // do stuff 
    } 

    // We now return a public API for our service. 
    return { 
    add: add, 
    store: store, 
    rm: remove 
    }; 
}; 

這是發展中AngularJS服務的很常見模式,它不需要在這些情況下,任何使用this

+0

我想了解服務和工廠之間的區別,但我認爲工廠本身應該是「返回」的,而服務不是:http://stackoverflow.com/questions/13762228/confused- about-service-vs-factory – 2013-02-15 23:14:09

+0

當我複製並粘貼你的代碼時,我忘了將它改成'.factory'。我更新了答案。服務是使用幾種模塊方法之一創建的。 'factory'返回你想要的任何東西,'service'只需要一個由提供者運行的構造函數,它返回新的對象。沒有訴諸一些JavaScript的魔術,你會想用'factory'來存儲異步操作的結果。 – 2013-02-15 23:26:01

+0

好吧,我已經通過做上面概述的'items'問題了,但是現在我遇到了同樣的問題,試圖在成功回調中調用與工廠不同的方法。我正在下載一些數據,如果下載成功,我想調用'store()'方法將其寫入localStorage。在你的代碼示例中,它就像調用'get()'方法一樣。 – 2013-02-17 22:10:04