AngularJS - 如何处理长期运行在控制器/服务所需要的数据请求 [英] AngularJS - how to handle long running requests for data needed in controller/services

查看:95
本文介绍了AngularJS - 如何处理长期运行在控制器/服务所需要的数据请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的角度应用程序首次加载,我需要做出一些相当大的数据一对夫妇的请求。此数据随后在控制器和服务所使用,以确定如何显示该网页。我收到各种JavaScript错误的,因为控制器和服务正在试图请求返回之前访问这些数据。

When my angular app first loads, I need to make a couple requests for some fairly large data. This data is then used in controllers and services to determine how to display the page. I'm getting all sorts of JavaScript errors because the controllers and services are trying to access this data before the request has returned.

我知道在HTML页面,可以绑定到这个异步数据和角将填充为你当请求返回。不过,我有一些pretty复杂的逻辑,在我的控制器和服务发生在此基础上的数据。所以,我想我有2个问题。

I know in the HTML pages, you can bind to this asynchronous data, and angular will populate it for you when the request returns. However, I have some pretty complex logic happening in my controllers and services based on this data. So, I guess I have 2 questions.


  1. 反正是有以某种方式与控制器和服务异步数据工作?

  2. 有没有一种方法,以prevent从试图渲染页面,直到数据返回后角?这基本上使得数据同步的要求,我确定这一点。这只是初始完整的HTML页面加载。

我在尝试的jsfiddle这显示出可以在这里找到: http://jsfiddle.net/sES9T/

My attempt at a jsFiddle showing this can be found here: http://jsfiddle.net/sES9T/

推荐答案

的基本流程应该是这样的:在内部控制器的功能,使$ HTTP请求,并在成功()回调,设置$范围变量必要的。是你的流量有什么不同?

The basic flow should be like this: Inside your controller function, make the $http request, and in the success() callback, set your $scope variables as needed. Is your flow different from that?

此外,使用 NG-节目指令来隐藏自己的DOM元素,直到范围有你需要的数据。

Also, use the ng-show directive to hide your DOM elements until the scope has the data you need.

您控制器将是这个样子:

Your controller will look something like this:

MyCtrl = ( $scope, $http ) ->
  promise = $http.get "/url"
  promise.success ( data ) ->
    $scope.foo = data

和你的观点会是这样的:

And your view will look like this:

div(ng-show="foo")
  p Here is my data, and some other stuff
  p {{ foo }}

修改

我在这里修改您的jsfiddle:

I've modified your jsfiddle here:

http://jsfiddle.net/sES9T/4/

据按预期工作,问题是,你试图在不确定的变量,这是抛出一个错误访问属性。此外,在第三次试验中,变量被命名为错误的,但仍然需要命名权当进行检查。

It works as expected, the problem was that you were trying to access properties on undefined variables, which was throwing an error. Also, on the third test, the variable was named wrong, but still needs to be checked when named right.

我推荐的CoffeeScript,因为这些if语句可以做了很多与运营商存在更简洁,像这样(?):

I'd recommend coffeescript, since those if statements can be made a lot more terse with the existential (?) operator, like so:

myLargeData?.data

这code会检查是否myLargeData正试图访问它之前定义的,非空的属性,就像我上面手工完成。如果是undefined或null,它将返回undefined,而不是导致错误。

That code will check if myLargeData is defined and non-null before trying to access it's properties, like I had done manually above. If it IS undefined or null, it will return undefined, instead of causing an error.

这篇关于AngularJS - 如何处理长期运行在控制器/服务所需要的数据请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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