Angular Service To Set And Retrieve Object Between Controllers

后端 未结 2 1171
失恋的感觉
失恋的感觉 2021-01-18 03:54

I been trying to set an service object from a http post response to a controller and getting it from another controller.
The tutorials I seen in SO or sites are focused

2条回答
  •  再見小時候
    2021-01-18 04:36

    @atinder answer is way to go. Here is the example of the service:

    app.service('StoreService',function(){
    
      var data1={};
      var data2={};
      this.save=function(data1,data2){        
           this.data1=data1;
           this.data2=data2;
    
      };
    
      this.getData1=function(){
    
        return data1;
    
      };
    
      this.getData2=function(){
    
        return data2;
    
      };
    });
    

    Then in first controller:

    .controller('firstController',function(StoreService){
        .....
        StoreService.save(resp.data.data1,resp.data.data2);
     });
    

    In second controller:

    .controller('secondController',function(StoreService,$scope){
        $scope.data1 = StoreService.getData1();
        $scope.data2 = StoreService.getData2();
     });
    

提交回复
热议问题