如何通过AngularJS路由保留数据? [英] How to preserve data through AngularJS routing?

查看:230
本文介绍了如何通过AngularJS路由保留数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是AngularJS的新手,正在尝试为自己构建一个简单的小应用程序.我有正在使用$resource提取的应用程序的JSON数据,并且该数据在多个视图/路由之间应该相同.但是,当我转到新路线时,JSON数据(存储为$scope.data)不再可用于新视图.我该怎么做才能将该数据传递到新视图,而无需再次获取? (本教程的电话目录应用程序每次都会根据我的判断重新获取此数据.)

I'm new to AngularJS and am trying to build myself a simple little app. I have JSON data for the app being fetched with $resource, and this data should be the same across multiple views/routes. However, when I go to a new route, the JSON data (stored as $scope.data) is no longer available to the new view. What can I do to pass this data to the new view and not require another fetch? (The tutorial phone-catalog app re-fetches this data every time from what I can tell.)

据我了解,$rootScope可以做到这一点,但似乎人们对此并不满意.如果这没有什么意义,我深表歉意.在这里,我非常想潜水.

From what I understand, $rootScope can do this but it seems to be generally frowned upon. I apologize if this doesn't make much sense; I'm very much diving in the deep end here.

推荐答案

使用服务存储数据.将该服务注入需要访问此数据的每个控制器中.每次创建并执行控制器时(因为您切换到另一个视图/路线),它都可以向服务请求数据.如果服务还没有数据,它可以向服务器发出请求,并向控制器返回承诺(有关操作方法,请参见下文).如果服务包含数据,则可以立即将其返回给控制器.

Use a service to store the data. Inject that service into each controller that needs access to this data. Each time a controller is created and executes (because you switch to another view/route), it can ask the service for the data. If the service doesn't yet have the data, it can make a request to the server and return a promise to the controller (see below for how to do that). If the service has the data, it can return it to the controller immediately.

另请参见在服务中处理$ http响应

请注意,与控制器不同,服务是单例的.

Note that services are singletons, unlike controllers.

另一个变体:创建服务时,它可以去获取数据本身,然后将其存储以备后用.控制器可以比$ watch服务上的属性或功能.有关此方法的示例,请参见如何存储Angular中当前的用户上下文?

Another variation: when the service is created, it can go fetch the data itself, and then store it for later use. Controllers can than $watch properties or functions on the service. For an example of this approach see How do I store a current user context in Angular?

这篇关于如何通过AngularJS路由保留数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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