Force AngularJS service to return data before loading controller

我与影子孤独终老i 提交于 2019-11-27 18:21:37
zs2020

You can make the factory to return a promise like this:

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngResource', 'infinite-scroll', 'ui.bootstrap', 'ngCookies', 'seo'])
    .service('userInfo', function ($http, $cookies) {
    var promise = $http.get('/api/users/' + $cookies.id).
    success(function (data) {
        var userInfo = data.user[0];
        return userInfo;
    });
    return promise;
}) // other stuff comes after this

And in your controller, do

function userProfile($scope, $cookies, userInfo, $http, $resource, $routeParams, $rootScope){
    userInfo.then(function(data){
        $scope.user = data;
    });
}

This can guarantee that whenever you use the service, it always gives you the data synchronously, you don't have to necessarily load any data before loading the controller.

Your userInfo service has to return the promise returned by $http. That promise will then be injected into your controller, and the view will be updated as soon as the promise successfully resolves.


If you don't want the view to be rendered at all before userInfo resolves, you should set a resolve property on your route, and inject your service there:

$routeProvider.when('/profile', {
    templateUrl: 'profile',
    controller: userProfile,
    resolve: {
         userInfoData: function ($q, userInfo) {
             return userInfo;
         }
    }
});

Then just inject userInfoData into your controller in place of the userInfo service.

You can assign the resource object to your variable like that return $http.get(url)

I've faced the same problem in which I had to load data into a service using $resource and get that data into controllers $scope. I didn't wanted to directly return the promise and then use a resolver in the controller (as @zsong wrote) but to do all the magic into the service once and use the ability to assign a promise directly to a $scope as @Joseph Silber point out, so here is what I did :

return function($scope){promise.then(function(data){$scope.user = data})};

And used it in the controller like this :

userInfo($scope);

Not much of an improvement but it allowed me a clearer syntax in my controllers, hope it'll help even three years later !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!