gpt4 book ai didi

javascript - Angular : $rootScope variable vs event

转载 作者:行者123 更新时间:2023-11-29 16:59:03 26 4
gpt4 key购买 nike

我正在处理一个管理用户登录的应用程序。像在许多应用程序中一样,我想在用户登录时更改标题。我有一个主文件 (index.html),它使用 ng-include 来包含 header.html

我找到了两个解决方案(我是 Angular 的新手,所以两个都可能是错误的):

1) 使用 $rootScope.broadcast()

因此,当用户登录时,我广播(auth.js,它位于 factory 内)一条消息,该消息被 header 中的 Controller 拦截。

auth.js

$rootScope.$broadcast('logged',user);

controller.js

$scope.$on('logged', function(evnt, message){
$scope.user = message;
});

header.html

<div class="header" ng-controller="GcUserCtrl as gcUserCtrl">
...
<li><a ng-show="user" href="#">User: {{user.name}}</a></li>

2) 设置一个 $rootScope 变量

据我所知,$rootScope 是所有范围的根(命名非常聪明)并且所有 $scope 都可以访问它。

auth.js

$rootScope.user=user;

heaeder.html(这里不需要 Controller )

<div class="header">
...
<li><a ng-show="user" href="#">User: {{user.name}}</a></li>

现在,正确的处理方式是什么?

  • 第一个似乎有点昂贵,因为广播可能需要做很多检查。
  • 第二个..好吧,我不喜欢全局变量..

编辑

3)使用服务

在 alex 的评论之后,我添加了这个选项,即使我无法让它工作。 ( here the plunkr )没有事件就无法工作

index.html

...
<ng-include src="'header.html'"></ng-include>
...

header.html

至于数字 1)

controller.js

.controller('GcUserCtrl', ['$scope','my.auth','$log', function ($scope, auth, $log) {
$scope.user = auth.currentUser();
}]);

my.auth.js

.factory('my.auth', ['$rootScope', '$log', function ($rootScope, $log, localStorageService) {
var currentUser = undefined;

return {

login: function (user) {
currentUser = user;
...

},

...
currentUser: function () {
return currentUser;
}
};
}]);

这里的问题是controller只是第一次被调用,登录后什么也没有发生。

最佳答案

如前所述,您将希望使用存储用户信息的服务。在您验证用户身份的任何地方将用户信息附加到此服务。如果您对最佳身份验证方式有疑问,那将是一个单独的问题,但您可能想研究使用执行实际身份验证(和任何授权)的登录工厂。然后您可以将登录服务注入(inject)该工厂。我创建了一个 Plunker here作为引用。

var app = angular.module('myApp', []);

app.service('SessionService', function () {
this.attachUser = function(userId, fName){
this.userId = userId;
this.fName = fName;
}
});


app.controller('MainCtrl', function($scope, SessionService){
// You will want to invoke attachUser some other way (perhaps on authentication), this is for test purposes only
SessionService.attachUser(1234, 'John');

$scope.userName = SessionService.fName;
});

上面的代码是您的服务的示例。这将充当 session 处理程序并存储有关用户的重要信息。 Controller MainCtrl 然后可以使用依赖注入(inject)调用 SessionService 中的属性。我在本文开头提到的部分 SessionService.attachUser(userId, fName) 很可能存在于登录工厂中。

这是最佳选择的原因是因为它解耦了您的应用程序。它将 session (实际上是您存储在全局变量中的内容)放在指定用于存储该数据的位置。它使它易于维护。例如,您不需要查找每次出现的 $rootScope。

编辑: New plunker使用 rootScope broadcast/on 来捕获变化

关于javascript - Angular : $rootScope variable vs event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774838/

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