angular.js - 关于angular中rest API 异步数据传送的问题

浏览:28日期:2023-02-05

问题描述

最近在做一个小项目,由于team里面缺少前端工程师,临时把我抓了过去写完全没有经验的angular。我看了一些基础的书,感到angular中的rest API 异步传输机制非常神奇。同时也在想,如果你的下一个http请求中的参数需要上一个请求get的结果,又该如何保证一定能拿到参数,不为空值。我试过将第二个或第三个等等http请求放在.success后面,确实是成功的,但是这样感觉代码非常冗余,嵌套层次也超级多。请问大家有什么建议?

问题解答

回答1:

楼主建议看看 promise 的嵌套 nest promise 和 promise 链式 promise chain

由于angular的$http 内置了两个快捷方法success 和 error 导致标准的then方法容易让人忽略.

楼主的需求 可以使用promise then的嵌套例如

$http1.post().then(function(data){ $http2.post(data.data).then(function(data){console.log(data); })})

或者用promise chain 链式

$http1.post().then(function(data){ return $http2.post(data.data);}).then(function(data){ console.log(data);})

不同的需求可以用不同的promise 形式

例如还有可以使用Q.all方法 使多个promise都完成在处理事件

回答2:

$http.get(’xxxxx’) .success(function(data){ $score.data = data; // do somethint... })

在success的里面操作,可以确保数据都获取到,这里有点像promise的链式调用。

回答3:

个人项目里作为baseService存在的一段代码:

/** * Created by thonatos on 14-11-14. */var ajaxService = angular.module(’ASS.service.ajaxService’, []) .factory(’ajaxService’, [’$http’, function ($http) {return ({ post: post, get: get, del: del, put: put});function post(url, data) { var promise = $http.post(url, data).then(function (response) {return response.data; }); return promise;}function get(url) { var promise = $http.get(url).then(function (response) {return response.data; }); return promise;}function del(url) { var promise = $http.delete(url, auth).then(function (response) {return response.data; }); return promise;}function put(url, data) { var promise = $http.put(url, data).then(function (response) {return response.data; }); return promise;} }]);module.exports = ajaxService;

下面是具体的postService:

/** * Created by thonatos on 14-11-8. */var _postUrl = ’/api/post’;var _postsUrl = ’/api/posts’var _user = ’thonatos’;var postService = angular.module(’ASS.service.postService’, []) .factory(’postService’, [’ajaxService’, function (ajaxService) {return ({ add: _add, del: _del, rev: _rev, get: _get, getAll: _getAll});function _add(post) { post.category = post.category.name; post.author = _user || ’nobody’; console.log(post); return ajaxService.post(_postUrl, post);}function _del(pid) { return ajaxService.delete(_postUrl + ’/’ + pid);}function _rev(pid, post) { return ajaxService.put(_postUrl + ’/’ + pid, post);}function _get(pid) { return ajaxService.get(_postUrl + ’/’ + pid);}function _getAll(pager) { return ajaxService.get(_postsUrl + ’/’ + pager);} }]);module.exports = postService;

最后在blogConroller里大概就是这样:

blog.controller(’blogPostCtrl’, [’$scope’, ’$stateParams’, ’postService’, function ($scope, $stateParams, postService) { var _pid = $stateParams.pid; var _post = {}; postService.get(_pid).then(function (response) {_post = response;$scope.post = _post; });}]);回答4:

如果后台保证良好的 REST 接口风格的话,建议使用 $resource 官方的插件:

app.factory ’User’, [’$resource’, ($resource)-> $resource ’/api/u/:name’, {name: '@name'} ]

这时就可以使用:

app.controller ’mainCtrl’, [’$scope’, ’User’, ($scope, User)-> ... ]

相关文章: