先看两个官方文档
https://docs.angularjs.org/api/ng/service/$http
http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/deferred-and-promise.html
首先呢 要知道$http和$.ajax一样 本身是可以直接链式的调用 .success .error 的(jQuery里面的ajax是failed)
那么为什么我还需要dfd呢 dfd更灵活,可以在很多地方使用 不仅仅局限于http请求
这里有个比较搓的例子 感受一下他们的区别
var list = dataSource.makeHttpRequest(‘/list‘, ‘POST‘, { "xxx": xxx }); list.httpRequest.success(function(data){ console.log(data); }); list.promise.then(function(data){ console.log(data); });
dataSource是我定义的一个factory 返回的httpRequest就是$http.post 而Promise则是dfd.promise
myApp.factory(‘dataSource‘, [‘$http‘, ‘$q‘, function($http, $q) { return { makeHttpRequest: function(url, method, params) { var httpRequest; var defer = $q.defer(); if (method == ‘GET‘) { //$http.get() } else if (method == ‘POST‘) { httpRequest = $http.post(url, params); httpRequest.success(function(data) { if (data.status == 0) { defer.resolve(data); } else { defer.reject(data); } }).error(function(msg) { defer.reject(msg); }); } return { promise: defer.promise, httpRequest: httpRequest } } } }]);
时间: 2024-11-15 12:06:33