Angular Service To Set And Retrieve Object Between Controllers

后端 未结 2 1172
失恋的感觉
失恋的感觉 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();
     });
    
    0 讨论(0)
  • 2021-01-18 05:01

    create a basic service with setters and getters. Inject the service into both the controllers. use setter in one controller and getter in the another.

    0 讨论(0)
提交回复
热议问题