suchen

Heim  >  Fragen und Antworten  >  Hauptteil

angular.js - angularjs 如何在controller中使用service

Service代码:

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代码:

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

controller的那句代码有问题。我用getTicketList.data也获取不到数据,是{}。而且不知道怎么把参数传进去。。。。

ringa_leeringa_lee2776 Tage vor760

Antworte allen(3)Ich werde antworten

  • 巴扎黑

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

    1.service里面用return代替this

    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.调用的时候使用promise模式

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

    Antwort
    0
  • 漂亮男人

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

    这种传递参数的方式是不对的,没这么用过,这里有个项目,找到对应的controller.service看看
    https://github.com/LittleDouBi/community

    Antwort
    0
  • 过去多啦不再A梦

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

    你应该使用promise模式:

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

    Antwort
    0
  • StornierenAntwort