2014-12-04 68 views
0

我知道數據來自服務器(我有單元測試,並看到調試器中的數據在鉻)但我不知道如何將角度服務的數據返回角度控制器。如何從角度js中的服務返回值?

服務:

修訂

surchargeIndex.service('customerService', [ 
'$http', function ($http) { 
    this.getTest = function() { 
     return $http({ 
       method: "GET", 
       url: "api/Customer/GetTest", 
      }) 
      .success(function(data) { 
       return data; 
      }); 
    }; 
} 

]);

控制器:

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) { 
    $scope.customers = customerService.getTest(); 

}); 

的數據具有從該服務器陣列,使得所述陣列被在服務填充。所以重申數據在那裏;但是,在調試期間,我收到成功處理程序的內部錯誤404。

我錯過了什麼?

回答

3

$http異步工作;幸運的是,它返回一個承諾,當從服務器檢索到響應時,它將被履行。所以你應該返回$ http的get方法並使用返回的promise來處理數據。

this.getTest = function() { 
     return $http({ 
       method: "GET", 
       url: "api/Customer/GetTest", 
      }) 
      .success(function(data) { 
       return data; 
      }) 
      .error(function() { 
       alert("failed"); 
     }); // This returns a promise 

    }; 

然後在您的控制器中,您應該使用該承諾來檢索預期數據。

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) { 
    //Use the returned promise to handle data, first parameter of the promise is used for successful result, if error happens, second parameter of the promise returns the error and you can do your error handling in that function 
    customerService.getTest().then(function(customers){$scope.customers = customers;}, function(err){console.error(err);}) 
}); 
+0

你說它返回一個「承諾」,這是什麼意思? – Robert 2014-12-04 15:06:01

+1

正如你可能知道JavaScript是異步工作的,所以當你通過'$ http'發出請求時,進程不會停止,直到它返回一個結果,但它會繼續執行下一個命令。通過返回一個承諾,你給調用者一個鉤子。當從服務器檢索到一個響應時,Promise將被執行,客戶端將通過promise的'then'函數被通知。您可能想要查看https://github.com/kriskowal/q這是廣泛使用的承諾實現之一。 – cubbuk 2014-12-04 15:10:24

+0

好的,數據有數組,但不返回給控制器。我得到了一個成功處理程序,但是當我調試它時,我在成功處理程序中返回了一個404數據返回數據。 – Robert 2014-12-04 15:19:37

0

您需要定義一個回調,讓您的數據「回」到你的控制器,一個異步HTTP調用後...有不同的方法去做......我會告訴你一個辦法,而不回調或承諾,但最好的方法是使用一個回調,或承諾...

狂野西部方式:

app.controller('myCTRL', function($scope, myService) { 

     $scope.valueWanted = myService.valueWanted; 
     myService.getData(); 

}); 

app.service('myService', function($http) { 

     var myThis = this; 

     this.valueWanted = ""; 
     this.getData = function() { 
       $http.get('api/Customer/GetTest').success(function (data) { 
        myThis.valueWanted = data.valueWanted; 
       }); 
     }; 

});