2017-07-29 43 views
0

这是我的角度服务代码。如何在服务中创建变量angularjs

'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; 
    } 
}]); 

我想添加一个变量并保存响应数据。像这样

//CommonService.Products = response.data; 

所以我可以直接在控制器中使用CommonService.Products并访问它。

但定义//CommonService.Products = [];给我错误。

如何在服务中定义变量以在控制器中使用它。

回答

0
CommonService.Products = response.data; 

此语句不会起作用,因为CommonServiceundefined在给定位置,和上下文。相反,你可以试试这个方法:

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); 
}];