2017-07-29 6 views
0

これは私のサービスコードです。サービスanglejsで変数を作成する方法

'use strict'; 

sampleApp.factory('CommonService', ['$http', '$q', function($http, $q){ 

    var REST_SERVICE_BILL_PRODUCT_URI = 'api/v1/billproducts'; 
    //CommonService.Products = []; 

    var factory = { 
     getBillProducts: getBillProducts, 
    }; 
    return factory; 

    function getBillProducts() { 
     var deferred = $q.defer(); 
     $http.get(REST_SERVICE_BILL_PRODUCT_URI) 
      .then(
       function (response) { 
        //CommonService.Products = response.data; 
        deferred.resolve(response.data); 
       }, 
       function(errResponse){ 
        console.error('Error while fetching bill products'); 
        deferred.reject(errResponse); 
       } 
      ); 
     return deferred.promise; 
    } 
}]); 

その中に1つの変数を追加してその中に応答データを保存したいと思います。このように

//CommonService.Products = response.data; 

私はCommonService.Productsをコントローラで直接使用し、アクセスに更新できます。

//CommonService.Products = [];を定義しています。私にエラーを与える。

サービスで変数を定義してコントローラで使用する方法。

答えて

0
CommonService.Products = response.data; 

CommonServiceは、与えられた場所、およびコンテキストでundefinedであるため、この文では動作しません。代わりに、このアプローチを試みることがあります。

sampleApp.factory('CommonService', ['$http', '$q', function($http, $q){ 
    // Store the reference of function's context here 
    var self = this; 

    // .. code truncated for brevity 

    .then(function (response) { 
    // Store response data into `Products` 
    self.Products = response.data; 
    deferred.resolve(response.data); 
    }, function(errResponse) { 

    // .. code truncated for brevity 

今、あなたは他のAngularJSコンポーネントでCommonServiceを注入し、簡単にこのようProductsを使用することができます。

sampleApp.controller("testController", ['CommonService', function(commonService) { 
    // Access products here 
    console.log(commonService.Products); 
}]; 
関連する問題