search

Home  >  Q&A  >  body text

angular.js - angularjs how to use service in controller

Service code:

app.service('getTicketList', function($q, $http){
    this.data = {};
    this.getData = function(id){
        var deferred = $q.defer();
        var path='ticket.action?method:projectTickets';
        if(id)
            path+='&projectId='+id.toString();
        $http.get(path).then(function(d){
            //success
            this.data = d;
            deferred.resolve(d);
        },function(){
            //failure
            deferred.reject(d);
        });
    }
});

controller code:

app.controller('projectController', function($scope,getTicketList) {
    $scope.tickets=getTicketList.getData($scope.projectId).data.tickets;
});

There is a problem with the controller code. I can't get the data using getTicketList.data, it's {}. And I don't know how to pass the parameters in. . . .

ringa_leeringa_lee2776 days ago758

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-05-15 16:52:58

    1. Use return instead of this in service

    javascriptapp.service('getTicketList', function ($q, $http) {
      var data = {};
      return {
        getData: function (id) {
          var deferred = $q.defer();
          var path = 'ticket.action?method:projectTickets';
          if (id)
            path += '&projectId=' + id.toString();
          var promise = $http.get(path).then(function (response) {
              return response;
          }, function (response) {
              return response
          });
          return promise;
        }
      }
    });
    

    2. Use promise mode when calling

    javascriptgetTicketList.getData($scope.projectId).then(
      function (res) {
        $scope.tickets = res.tickets
      }, 
      function (rej) {
      // error handler
      }
    );
    

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-15 16:52:58

    This way of passing parameters is wrong. I have never used it like this. There is a project here. Find the corresponding controller.service and have a look
    https://github.com/LittleDouBi/community

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-15 16:52:58

    You should use promise mode:

    app.service('getTicketList', function ($q, $http) {
      this.data = {};
      this.getData = function (id) {
        var deferred = $q.defer();
        var path = 'ticket.action?method:projectTickets';
        if (id) {
          path += '&projectId=' + id.toString();
        }
        return $http.get(path).then(function (d) {
          this.data = d;
          return $q.when(d);
        }, function (d) {
          return $q.reject(d);
        });
      }
    });
    
    app.controller('projectController', function ($scope, getTicketList) {
      getTicketList.getData($scope.projectId).then(function (res) {
        $scope.tickets = res.tickets
      }, function (rej) {
        // error handler
      });
    });
    

    reply
    0
  • Cancelreply