Processing $http response in service

后端 未结 12 1627
半阙折子戏
半阙折子戏 2020-11-22 03:36

I recently posted a detailed description of the issue I am facing here at SO. As I couldn\'t send an actual $http request, I used timeout to simulate asynchrono

12条回答
  •  有刺的猬
    2020-11-22 04:18

    Please try the below Code

    You can split the controller (PageCtrl) and service (dataService)

    'use strict';
    (function () {
        angular.module('myApp')
            .controller('pageContl', ['$scope', 'dataService', PageContl])
            .service('dataService', ['$q', '$http', DataService]);
        function DataService($q, $http){
            this.$q = $q;
            this.$http = $http;
            //... blob blob 
        }
        DataService.prototype = {
            getSearchData: function () {
                var deferred = this.$q.defer(); //initiating promise
                this.$http({
                    method: 'POST',//GET
                    url: 'test.json',
                    headers: { 'Content-Type': 'application/json' }
                }).then(function(result) {
                    deferred.resolve(result.data);
                },function (error) {
                    deferred.reject(error);
                });
                return deferred.promise;
            },
            getABCDATA: function () {
    
            }
        };
        function PageContl($scope, dataService) {
            this.$scope = $scope;
            this.dataService = dataService; //injecting service Dependency in ctrl
            this.pageData = {}; //or [];
        }
        PageContl.prototype = {
             searchData: function () {
                 var self = this; //we can't access 'this' of parent fn from callback or inner function, that's why assigning in temp variable
                 this.dataService.getSearchData().then(function (data) {
                     self.searchData = data;
                 });
             }
        }
    }());

提交回复
热议问题