gpt4 book ai didi

AngularJS 将逻辑放在服务中而不是 Controller 中,最佳实践

转载 作者:行者123 更新时间:2023-12-02 01:39:27 25 4
gpt4 key购买 nike

我有一个从 Firebase 收集数据的 Controller 。我在我的整个网站上都使用它,所以它一直被调用。

app.controller("ReplicatedController", function($scope, $routeParams, $firebaseObject) {

var parts = location.hostname.split('.');
var refSubdomain = parts.shift();

var ref = new Firebase("https://example-firebase.firebaseio.com/" + refSubdomain);
var syncObject = $firebaseObject(ref);
syncObject.$bindTo($scope, "coach");

if($routeParams.my_affiliate){
var myAffiliate = $routeParams.my_affiliate;
window.location = "http://" + myAffiliate + ".example.com";
};

});

这工作得很好,但我的问题是我应该将它移到服务中吗?这会不会让我访问我的 Firebase 的频率降低?

还有什么是将类似的东西移动到服务中的最佳方法。我只是创建一个服务吗?

app.factory('ReplicatedService', ['$http', function($scope, $routeParams, $firebaseObject){
var parts = location.hostname.split('.');
var refSubdomain = parts.shift();

var ref = new Firebase("https://example-firebase.firebaseio.com/" + refSubdomain);
var syncObject = $firebaseObject(ref);
syncObject.$bindTo($scope, "coach");

if($routeParams.my_affiliate){
var myAffiliate = $routeParams.my_affiliate;
window.location = "http://" + myAffiliate + ".example.com";
};

});

然后从我的 Controller 调用服务?

app.controller('ReplicatedController', ['$scope','ReplicatedService', function($scope,ReplicatedService){

}]);

我似乎无法让它工作。还有为什么我需要改变它?它会提高性能,还是只会使代码更清晰、更易读?

最佳答案

您的工厂供应商没有退回任何东西。要访问它,您需要实际返回同步对象。

app.factory('ReplicatedService', ['$http', function($scope, $routeParams, $firebaseObject){
var parts = location.hostname.split('.');
var refSubdomain = parts.shift();

...

return syncObject;
});

app.controller('...', function(ReplicatedService) {
$scope.data = ReplicatedService;
});

这是一个通过化简调试的典型案例。要自己解决这个问题,您首先要将其分解为您能想到的最小工作组件:

app.factory('test', function() {
return { foo: 'bar' };
});

app.controller('...', function($scope, test) {
$scope.test = test;
});

然后逐个添加组件,直到它损坏或按预期工作。处理多种新技术和概念时的好方法。

关于AngularJS 将逻辑放在服务中而不是 Controller 中,最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29309965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com