AngularJS。关于适当的双向数据服务结合最佳实践 [英] AngularJS. Best practice concerning proper two way data binding from a service

查看:212
本文介绍了AngularJS。关于适当的双向数据服务结合最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个账户服务,充当多个控制器和视图中使用一个集中的数据存储。该服务将举行,除了getter和setter方法​​有两种类型的用户相关的所有数据,作为一个登录的用户和用户anomonous

I have an 'Account' service which acts as a centralized data storage used in multiple controllers and views. This service will hold, besides getter and setter methods all data associated with two types of users, being a logged in user and an anomonous user.

此服务背后的想法是,它应该被用来作为一个集中的数据结构,其将保持同步所有相关视图和控制器。例如:如果在磨片就知道了他的电子邮件和所有的新闻订阅用户登录字段可以是prefilled

The idea behind this service is that it should be used as a centralized data structure which will keep all associated views and controllers in synch. Eg: If a user logs in whe will know his email and all 'newsletter subscription' fields can be prefilled.

目前的设置我用的是如下。请注意,服务器上的每个异步调用将返回一个承诺。

The current setup i use is as below. Note that each Async call on the server will return a promise.

// The Service
angular.module('A').provider('AccountService', [function() {

    this.$get = function ($resource) {

        var Account = {
            getLoggedInAccountAsync : function () {
              var Account = $resource(WebApi.Config.apiUrl + 'Account/Get');
              return Account.get();
            },

            getUserData : function () {
                return Account.userData; 
            },

            setUserData : function (accountData) {
                var merge = angular.extend((Account.currentAccountData || {}), accountData);
                Account.currentAccountData = merge; 
            }    
        };

        return Account;
    }
});

// Our main app controller. Get's fired on every page load.
angular.module('A').controller('MainController', ['AccountService', function (AccountService) {

    var loggedInAccount = AccountService.getLoggedInAccountAsync();
    loggedInAccount.$then(loggedInAccountPromiseResolved);

    function loggedInAccountPromiseResolved (response) {
       if (response.data.isLoggedIn) {
           AccountService.setAccountData(response.data);
       }
    };

    return $scope.MainController= this;
}])

// Our specific controller. For example a newsletter subscription.
angular.module('A').controller('SpecificController', ['AccountService', function (AccountService) {
    this.getUserData = AccountService.getUserData;
    return $scope.Controller = this;
}])

// Newsletter subscription view
<input id="email" type="email" name="email" ng-model="SpecificController.getUserData().UserName"/>

使用上述code确保每当我们使用该服务通过Controller.getUserData()。酒店给我们的看法绑定我们的数据将保持同步,我们整个应用程序。

Using the above code ensures that whenever we use the service to bind our data via Controller.getUserData().property to our view it will stay in synch throughout our entire app.

的code以上也将引发如果例如没有定义.UserName值,或者如果在所有在anomonous用户的情况下,没有考虑数据。解决此问题的方法是我们与空值的服务内'倾倒'我们的'模板'对象,这将确保键/值存在。另一种方法是使用观察者,并让我们的控制器(S)的情况下,'写'对我们的服务的用户填写一个字段。

The code above will also throw if for example the .UserName value is not defined, or if there is no account data at all in case of an anomonous user. One way around this is to 'dump' our 'template' object within our service with null values this will ensure the key/values exist. Another way would be to use watchers and let our controller(s) 'write' to our service in case an user fills a field.

第一个方案给我,我可以集中所有的数据服务绑定更多的flexability但感觉肮脏的,因为你永远不知道会与服务器进行数据发生什么,它可能进来作为例如不同的格式。

The first option gives me more flexability as i can centralize all the data binding in the service but it feels dirty because you never know what will happen with the server data, it could come in as a different format for example.

有没有人有任何其他解决方案?我想preFER不让我做的控制器的数据写入到该服务。

Does anyone have any other solution? I would prefer to not let my controllers do the writing of the data to the service.

感谢您的时间!

推荐答案

有很多问题在这里,因为我会尽全力为最佳答案。

There are many questions here, I will answer as best as I can.

没有,你在做什么不是最佳实践。

No, what you are doing is not a "best practice".

首先,该模型应当直接注射到视图中,并保持该值是控制器的责任,以$范围的帮助。您的NG模型=Controller.getUserData()。用户名是坏的。还有就是在博客文章中,我注意到下面的到底是什么做的一个很好的例子。

First, The model should be injected directly into the view, and maintaining the value is the responsibility of the Controller, with the help of "$scope". Your "ng-model="Controller.getUserData().UserName" is bad. There is a good example of what to do in the end of the blog article I noticed below.

二,当你从服务中获取数据,大多数时候,答案将是异步的,所以你最好先看看无极API。 AngularJS的官方文档并不总是美妙的,有时答案可以在谷歌团体或博客文章中找到。

Second, when you fetch data from a service, most of the time, the answer will be asynchronous, so you'd better take a look at the Promise API. The official doc of AngularJS is not always fantastic and sometimes the answer can be found on google groups or in blog article.

有关您的问题,这里是一个很好的文章:的http:/ /markdalgleish.com/2013/06/using-promises-in-angularjs-views/

For your problem, here is a good article : http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

这篇关于AngularJS。关于适当的双向数据服务结合最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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