Angularjs 数据存储最佳实践 [英] Angularjs Best Practice for Data Store

查看:40
本文介绍了Angularjs 数据存储最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 angular 应用有 2 个控制器.我的问题是,当用户离开页面时,控制器不会保留数据.

如何将选定的控制器上的数据存储到数据存储中,以便在其他控制器之间使用?

解决方案

Option 1 - custom service

您可以利用专用的 Angular 服务在控制器之间存储和共享数据(服务是单实例对象)

服务定义

 app.service('commonService', function ($http) {变量信息;返回 {获取信息:获取信息,设置信息:设置信息};//...................函数 getInfo() {返回信息;}函数 setInfo(value) {信息 = 价值;}});

在多个控制器中的使用

app.controller("HomeController", function ($scope, commonService) {$scope.setInfo = 函数(值){commonService.setInfo(value);};});app.controller("MyController", function ($scope, commonService) {$scope.info = commonService.getInfo();});

<小时>

选项 2 - html5 localStorage

您可以使用内置的浏览器本地存储,随时随地存储您的数据

写作

$window.localStorage['my-data'] = 'hello world';

阅读

var data = $window.localStorage['my-data']//...

<小时>

选项 3 - 通过网络服务器 api

如果你需要在不同用户之间持久化数据,你应该把它保存在服务器端的某个地方(数据库/缓存)

function getProfile() {返回 $http.get(commonService.baseApi + '/api/profile/');}函数更新配置文件(数据){var json = angular.toJson(data);返回 $http.post(commonService.baseApi + '/api/profile/', json);}

My angular app have 2 controllers. My problem is that the controllers does not keep the data when the user navigates away from the page.

How can I store the selected data on of my controllers into a data store so it can be used between other controllers?

解决方案

Option 1 - custom service

You can utilize a dedicated angular service to store and share data between controllers (services are single instance objects)

service definition

 app.service('commonService', function ($http) {

        var info;

        return {
            getInfo: getInfo,
            setInfo: setInfo
        };

        // .................

        function getInfo() {
            return info;
        }

        function setInfo(value) {
            info = value;
        }
});

usage in multiple controllers

app.controller("HomeController", function ($scope, commonService) {

    $scope.setInfo = function(value){
        commonService.setInfo(value);
    };

});


app.controller("MyController", function ($scope, commonService) {

    $scope.info = commonService.getInfo();

});


Option 2 - html5 localStorage

You can use the built-in browser local storage and store your data from anywhere

writing

$window.localStorage['my-data'] = 'hello world';

reading

var data = $window.localStorage['my-data']
// ...


Option 3 - via web server api

If you need to persist data among different users, you should save it somewhere in the server side (db / cache)

function getProfile() {
    return $http.get(commonService.baseApi + '/api/profile/');
}

function updateProfile(data) {
    var json = angular.toJson(data);
    return $http.post(commonService.baseApi + '/api/profile/', json);
}

这篇关于Angularjs 数据存储最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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