angular.js - How to call multiple services at the same time in angularjs?
某草草
某草草 2017-05-15 16:52:24
0
3
613

Two services are defined in the project, get task and project, what if we get their data together in the controller and then assign values? Currently, I use

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

Could you please tell me how to write the $q method, and I will use this data acquisition operation in many places, how to make them reuse? Thank you

某草草
某草草

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