在加载控制器之前强制 AngularJS 服务返回数据 [英] Force AngularJS service to return data before loading controller

查看:24
本文介绍了在加载控制器之前强制 AngularJS 服务返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular 中有一项服务,它使用我的 API 来获取用户信息并将其提供给我的控制器.设置如下:

I have a service in Angular which uses my API to get user information and provides it to my controllers. It's set up like this:

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

      return userInfo;
    });
  }). // other stuff comes after this

在我的控制器中,我包括它:

In my controllers, I include it like:

function userProfile($scope, $cookies, userInfo, $http, $resource, $routeParams, $rootScope){
    $scope.user = userInfo;
    console.log('user info is')
    console.log(userInfo);

这不返回任何数据,而如果我在控制器本身中放置相同的服务功能,它返回就好了.我在这里缺少什么?之前从未在 Angular 中使用过 DI/Services,所以可能是某个地方的一个简单错误.

This is returning no data, while if I put the same service function in the controller itself it returns just fine. What am I missing here? Never used DI/Services in Angular before so might be a simple mistake somewhere.

我需要确保服务在控制器加载之前返回数据.这是怎么实现的

I need to ensure that the service returns data before the controller loads. How can this be accomplished

推荐答案

你可以让工厂返回这样的承诺:

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

在你的控制器中,做

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.

这篇关于在加载控制器之前强制 AngularJS 服务返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆