84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
在项目定义了两个服务,获取task和project,如果在controller中一起获取他们的数据然后进行赋值呢?目前我是通过
task
project
jstaskService.get({id:id},function(data1){ //... projectService.get({id:id},function(data2){ //里面赋值的操作很长 ... }) })
js
taskService.get({id:id},function(data1){ //... projectService.get({id:id},function(data2){ //里面赋值的操作很长 ... }) })
请问大神们采用$q的方式应该如何写,还有我在很多地方会用到这个获取数据的操作,如何让他们复用呢?谢谢
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){ // 错误处理 }); }]);
javascript
myApp.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(....) }
// 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){ //里面赋值的操作很长 });
Written according to your requirements, you can see the code below:
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: