Answer the question
In order to leave comments, you need to log in
How to inject a service with a promise in the scope and not run into an Infinite $digest Loop?
Hello!
I can’t solve one problem in any way :( The task is: to make an ACL. The list of permissions is loaded from the server. Next, I check if the user has access to such and such a resource by viewing the resulting list. For convenience, I implement the created service in the scope as a call a dynamic function that checks whether the user has the right to access the resource.Since I can’t work here without a promise (after all, the data comes from the server) - when it is returned and working with scope, I quite deservedly get an Infinite $digest Loop error. I can't figure out how to get around it,
even if I simplify the example to the simplest level:
module.factory('ACL', function ($q) {
return {
access: function () {
return $q.when(true);
}
};
});
$rootScope.access = ACL.access;
<div ng-if="access()"></div>
Answer the question
In order to leave comments, you need to log in
Реализовать задачу можно примерно так:
module.service('ACL', function () {
var self = this;
// Разрешения.
self.permissions;
// Инициализация списка разрешений.
promise.then(function (data) {
self.permissions = ...;
});
// Проверка доступа.
self.access = function (permission) {
if (angular.isDefined(self.permissions)) {
return permission in self.permissions;
}
};
});
Вы понимаете, что даже если бы ангуляр не уходил в бесконечный digest вы значение true не получили бы?
Сделайте в котроллере вашей вьюшки какое-то свойство, которое будет как-то так инициализироваться:
access().then(function(data) {
if (data.foo) {
vm.hasAccess = true;
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question