AngularJS - 依赖注入涉及异步数据 [英] AngularJS - Dependency injection involving asynchronous data

查看:209
本文介绍了AngularJS - 依赖注入涉及异步数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在提供给我的角度指示用户的ID和用户名当前登录。我已经创建了一个API端点检索这些信息(有一些其他信息)。

I want to make the currently logged in user's ID and user name available to my Angular directives. I have created an API end-point to retrieve this information (along with some other information).

的问题是,所述API调用是异步

The problem is that the API call is asynchronous:

var url = baseUrl + 'api/sessions';
$http.get(url)

我想创建一个工厂,将返回API返回的JSON对象。然而,由于调用是异步的,我不知道如何实现工厂方法。

I am trying to create a factory that will return the JSON object returned by the API. However, since the call is asynchronous, I don't know how to implement the factory method.

此外,我不想实例化指令,直到值来自API回来之后。是否有内置于AngularJS,将确保异步调用已返回第一个,或者我应该只创建一个全局对象,并更新其值的机制,当调用返回(使用JSON对象)?

Additionally, I don't want to instantiate the directives until after the value comes back from the API. Is there a mechanism built in to AngularJS that will make sure the asynchronous call has returned first, or should I just create a global object and update its values when the call returns (using the JSON object)?

这是我目前有:

application.factory('session', ['$http', 'baseUrl', function ($http, baseUrl) {
    var session = {};
    var url = baseUrl + 'api/sessions';
    var promise = $http.get(url)
        .success(function (data) {
            for (var key in data) {
                session[key] = data[key];
            }
        });
    return session;
}]);

问题是,任何相关的指令获取会话对象填充之前。我很担心,如果API调用需要很长的时间,会话对象,当用户去使用它被初始化。

The problem is that any dependent directives are retrieving the session object before it is populated. I am concerned that if the API call takes a long time, the session object will be uninitialized when the user goes to use it.

推荐答案

原来,当涉及到AngularJS我跟随pretty讨厌的反模式。我在我的HTML绑定属性的功能。大多数情况下,这是在 NG-禁用=isThisFieldDisabled()

It turns out I was following a pretty nasty anti-pattern when it comes to AngularJS. I was binding attributes to functions in my HTML. Most often, this was in the form of ng-disabled="isThisFieldDisabled()".

问题是我是否计算领域应在每次函数被调用时被禁用。在数据被异步加载的情况下,这些功能首先需要检查,如果这些数据是被加载。

The problem was I was calculating whether the field should be disabled every time the function was called. In cases where the data was loaded asynchronously, these functions would first need to check if the data had been loaded yet.

function ($scope, someFactory) {

    someFactory.then(function (data) {
        $scope.data = data;
    });

    $scope.isThisFieldDisable = function () {
        if (!angular.isDefined($scope.data)|| $scope.data === null) {
            return true;
        }
        return $scope.data.someCondition;
    };
}

一个更容易的方法是简单地更新状态,当数据从调用返回:

A much easier approach is to simply update the condition when the data is returned from the call:

function ($scope, someFactory) {

    $scope.someCondition = true;

    someFactory.then(function (data) {
        $scope.someCondition = data.someCondition;
    });

    $scope.isThisFieldDisable = function () {
        return $scope.someCondition;
    };
}

当然,一旦你只是返回 $范围值,函数变得不必要了。您可以随时更新,像这样 NG-禁用=someCondition的HTML 和控制器结束了更加直截了当:

Of course, once you are just returning the $scope value, the function becomes unnecessary. You can update the HTML like so ng-disabled="someCondition" and the controller ends up much more straight-forward:

function ($scope, someFactory) {

    $scope.someCondition = true;

    someFactory.then(function (data) {
        $scope.someCondition = data.someCondition;
    });
}

在大多数情况下,我竟然将我的 $范围功能集成到本地功能。它们包含的逻辑心计的支持字段的值,因此这是有意义从 $ HTTP 回调调用它们。我通常不得不添加参数,因为我并没有倾销尽可能多的 $范围了。

In most cases, I actually converted my $scope functions into local functions. They contained the logic for "calculating" the value of the backing field, so it made sense to call them from the $http callbacks. I usually had to add parameters since I wasn't dumping as much in the $scope anymore.

这篇关于AngularJS - 依赖注入涉及异步数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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