Angularjs的$http非同步刪除資料詳解及執行個體,angularjs非同步
Angularjs的$http非同步刪除資料詳解及執行個體
有人會說刪除這東西有什麼可講的,寫個刪除的service,controller調用一下不就完了。
嗯...看起來是這樣,但是具體實現起來真的有這麼簡單嗎?首先有以下幾個坑
怎麼確定資料是否刪除成功?
怎麼同步視圖的資料庫的內容?
1.思路
1.實現方式一
刪除資料庫中對應的內容,然後將$scope中的對應的內容splice
2.實現方式二
刪除資料庫中對應的內容,然後再reload一下資料(也就是再調用一次查詢方法,這種消耗可想而知,並且還要保證先刪除資料再查詢)
2.具體實現方式
刪除資料的service:用非同步,返回promise
service('deleteBlogService',//刪除部落格 ['$rootScope', '$http', '$q', function ($rootScope, $http, $q) { var result = {}; result.operate = function (blogId) { var deferred = $q.defer(); $http({ headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, url: $rootScope.$baseUrl + "/admin/blog/deleteBlogById", method: 'GET', dataType: 'json', params: { id: blogId } }) .success(function (data) { deferred.resolve(data); console.log("刪除成功!"); }) .error(function () { deferred.reject(); alert("刪除失敗!") }); return deferred.promise; }; return result; }])
controller裡面注意事項
要特別注意執行順序:確保己經刪除完成之後再去reload資料,不然會出來視圖不更新
/** * 刪除部落格 */ $scope.deleteBlog = function (blogId) { var deletePromise = deleteBlogService.operate(blogId); deletePromise.then(function (data) { if (data.status == 200) { var promise = getBlogListService.operate($scope.currentPage); promise.then(function (data) { $scope.blogs = data.blogs; $scope.pageCount = $scope.blogs.totalPages; }); } }); };
以上就是Angularjs的$http非同步刪除資料的執行個體詳解,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!