Wpis z mikrobloga

Mircy mam taki serwis:

.service('Auth',['$http','TokenStorage','$rootScope', function($http, TokenStorage, $rootScope) {
var authenticated = false;
var username = {};

this.getAuthenticated = function () {
return authenticated;
},

this.init = function () {
$http.get('http://localhost:8080/api/users/current').success(function (user) {
if(user.username !== 'anonymousUser'){
authenticated = true;
username = user.username;
}
});
};

this.login = function (username, password) {
$http.post('http://localhost:8080/api/login', { username: username, password: password }).success(function (result, status, headers) {
authenticated = true;
TokenStorage.store(headers('X-AUTH-TOKEN'));
});
};

this.logout = function () {
TokenStorage.clear();
authenticated = false;
};

}])

i chce zeby zmienna authenticated aktualizaowała sie w całym projekcie.

Wiem, że można to zrobic przy pomocy watcha, ale jak to zrobic przy pomocy broadcast ;d Co wpisac w serwisie($broadcast tylko jak) i co wpisac w glownym kontrolerze app($on tylko jak):

angular.module('app')
.controller('AppCtrl',[ 'Auth' ,function (Auth) {
var app = this;

$scope.authenticated = Auth.getAuthenticated();

}]);

#angularjs
  • 6
Po zalogowaniu, tam gdzie masz authenticated = true;, powinieneś wywołać $rootScope.$broadcast('auth.loggedin') (nazwa tutaj jest dowolna, ważne, by była wszędzie jednolita). W głównym kontrolerze natomiast $rootScope.$on('auth.loggedin', function() { /* użytkownik został zalogowany */ }). To najprostsze rozwiązanie.
@Greenek: prawie działa ;d tylko po odświeżeniu strony authenticated jest undefined.

.service('Auth',['$http','TokenStorage','$rootScope', function($http, TokenStorage, $rootScope) {
var authenticated = false;
$rootScope.$broadcast('auth.loggedout');
var username = {};

this.getAuthenticated = function () {
return authenticated;
},

this.init = function () {
$http.get('http://localhost:8080/api/users/current').success(function (user) {
if(user.username !== 'anonymousUser'){
authenticated = true;
$rootScope.$broadcast('auth.loggedin');
username = user.username;
}
});
};

this.login = function (username, password) {
$http.post('http://localhost:8080/api/login', { username: username, password: password }).success(function (result, status, headers) {