AngularJS service http success function using wrong “this” scope

后端 未结 2 563
逝去的感伤
逝去的感伤 2021-02-01 07:58

The success function of a $http.put doesn\'t have access to the this scope of the service it\'s being called inside. I need to update a property of the

相关标签:
2条回答
  • 2021-02-01 08:41

    Create a closure over a variable (often called that) that is assigned to this so that your callback functions will have access to your service object:

    app.service('CatalogueService', function($rootScope, $http) {
        var that = this;
        ...
            ).success(function(data,status,headers,config) {
              that.items.push(data);
    

    Here is a Plunker that uses $timeout instead of $http to demonstrate.

    0 讨论(0)
  • 2021-02-01 08:48

    As far as I know, you can't. But I wouldn't try to run the service that way anyway. Here is a cleaner way:

    .factory('CatalogueService', function($rootScope, $http) {
      // We first define a private API for our service.
    
      // Private vars.
      var items = [];
    
      // Private methods.
      function add( id ) {
        $http.put( $rootScope.apiURL, {id:id} )
        .success(function(data,status,headers,config) { items.push(data); })
        .then(function(response) { console.log(response.data); });
      }
    
      function store( obj ) {
        // do stuff
      }
    
      function remove( obj ) {
        // do stuff
      }
    
      // We now return a public API for our service.
      return {
        add: add,
        store: store,
        rm: remove
      };
    };
    

    This is a very common pattern of developing services in AngularJS and it doesn't require any use of this in these cases.

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