angular.js - angularjs中的多个服务同时多次如何调用?
某草草
某草草 2017-05-15 16:52:24
0
3
578

在项目定义了两个服务,获取taskproject,如果在controller中一起获取他们的数据然后进行赋值呢?目前我是通过

jstaskService.get({id:id},function(data1){
    //...
    projectService.get({id:id},function(data2){
        //里面赋值的操作很长
        ...
    })
})

请问大神们采用$q的方式应该如何写,还有我在很多地方会用到这个获取数据的操作,如何让他们复用呢?谢谢

某草草
某草草

reply all(3)
滿天的星座

Written according to your requirements, you can see the code below:

javascriptmyApp.controller("MyController", ["$q", "taskService", "projectService", function($q, taskService, projectService){
    var deferred = $q.defer();
    var promise = deferred.promise;

    deferred.resolve(
        // 获取你要处理的对象
        var result = yourMethod.get({id: id});
    );
    deferred.reject(
        // 获取不到是打印错误
    )

    promise.then(function(result){
        // 如果经过taskService处理的数据还需要projectService进行处理的话,返回这个结果
        var obj = taskService.func(result);
        return obj;
    },function(error){ 
        // 错误处理
    })
        .then(function(result){
        // 用projectService处理获取到的对象
        projectService.func(result);
    },function(error){
        // 错误处理
    });
}]);

If you want to reuse it, you can treat the whole thing as a service. Since I don’t know your specific code, it’s hard to say.

伊谢尔伦

You can add a method to the service, and it will be OK to get two at the same time, for example:

js// someService 中 伪代码
someService.getAll = function(id) {
  var pmo = $q.all([taskService.get({id:id}), projectService.get({id:id})]);
  // 根据情况,可以写下边的代码,也可以直接返回这个pro
  pmo.then(....)
}
刘奇
taskService.sub1 = function(post_data, callback) {
    projectService.get(post_data, function(rsp){
        if(angular.isFunction(callback)) {
            callback(rsp);
        }
    }
}

taskService.sub1({ id : 1 }, function(rsp){
    //里面赋值的操作很长
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template