简体   繁体   中英

How to get data from Angularjs Service Response to Controller Scope Object

I am having simple Angularjs 1.7 app. Everything works fine and I am able to fetch data from web API to angularjs service. When I debug on Angularjs service I can see that data is being fetched from database via Web API. So I am using the service inside angularjs controller to fetch the data into scope object. But I am not sure why the data is not being fetched in controller scope object. Is there anything that I am missing to fix it.

Service.js

(function () {

    var app = angular.module('myApp');

    app.factory('websiteService', function ($http, $q) {
        var factory = [];
        var deferred = $q.defer();
        var baseURI = 'http://localhost:59029/api';

        factory.getAllStudents = function () {
            $http({
                method: 'GET',
                url: baseURI + '/Website/GetAllStudents'
            }).then(function (response) {
                deferred.resolve(response);
            }, function (error) {
                deferred.reject(error);
            });
            return deferred.promise;
        }

        return factory;
    });
})();

Controller.js

(function () {

    var app = angular.module('myApp');

    app.controller('websiteController', ['$scope', '$http', 'websiteService', '$filter',
        function ($scope, $http, websiteService, $filter) {
            $scope.TestWebsite = "TestWebsite";
            console.log($scope.TestWebsite);

            //GET Students
            websiteService.getAllStudents()
                .then(function (response) {
                    $scope.FetchedAllStudents = response;
                    // NOT ABLE TO FETCH THE DATA HERE
                }, function (error) {
                    // error handling here
                });
        }
    ]);
})();

There is no need to manufacture a promise with $q.defer as the $http service already returns a promise:

app.factory('websiteService', function ($http, $q) {
    var factory = [];
    ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
    var baseURI = 'http://localhost:59029/api';

    factory.getAllStudents = function () {
        return $http({
            method: 'GET',
            url: baseURI + '/Website/GetAllStudents'
        }).then(function (response) {
            return response.data;
        });
    }
    return factory;
});

For more information see Is this a "Deferred Antipattern"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM