How to preserve data through AngularJS routing?

后端 未结 1 1304
天涯浪人
天涯浪人 2020-12-14 10:44

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

相关标签:
1条回答
  • 2020-12-14 11:36

    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.

    See also Processing $http response in service

    Note that services are singletons, unlike controllers.

    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?

    0 讨论(0)
提交回复
热议问题