I have a angular service like this:
videoApp.factory('cacheLoader', function ($http, $filter, $rootScope) {
this.self = this;
return {
load: function (url, allowCache) {
if(allowCache == false || localStorage.getItem(url) && (parseInt(localStorage.getItem(url + 'time')) + 20000) < (new Date().getTime()) || (!localStorage.getItem(url) )) {
$http.get(url).success(function (data) {
$rootScope.allData = data;
$rootScope.videos = data;
$rootScope.categories = $filter('categoryFilter')(data);
if(allowCache == true && parseInt(localStorage.getItem(url + 'time')) + 20000 < (new Date().getTime() )) {
localStorage.setItem(url, JSON.stringify(data));
localStorage.setItem(url + 'time', new Date().getTime());
}
});
} else {
$rootScope.allData = JSON.parse(localStorage.getItem(url));
$rootScope.videos = JSON.parse(localStorage.getItem(url));
$rootScope.categories = $filter('categoryFilter')(JSON.parse(localStorage.getItem(url)));
}
},
getFilteredResults: function (category, data, callback) {
callback = callback || $filter('articleFilter');
$rootScope.videos = callback(category, data);
return $rootScope.videos;
}
};
});
Now, what I want to use cacheLoader.getFilteredResults inside cacheLoader.load function. this is a window object, so I can't point on it, I tried to bind this to the whole module pattern, but it throw error.
Is there any way how to accomplish what I'm trying to?
You should be able to use this.getFilteredResults inside the load method:
videoApp.factory('cacheLoader', function ($http, $filter, $rootScope) {
this.self = this;
return {
load: function () {
this.getFilteredResults();
},
getFilteredResults: function () {
alert('hi');
}
};
});
And if you need to handle referring to this inside a callback, then do something like:
return {
load: function () {
var that = this;
doSomeThing().then(function(data) {
that.getFilteredResults();
});
},
getFilteredResults: function () {
alert('hi');
}
};
Related
I have this controller here that calls a service, it works fine, however I needed to call a method that is inside that service in another module. How can I do this?
BaSiderbarService:
(function() {
'use strict';
angular.module('BlurAdmin.theme.components')
.provider('baSidebarService', baSidebarServiceProvider);
/** #ngInject */
function baSidebarServiceProvider() {
var staticMenuItems = [];
this.addStaticItem = function() {
staticMenuItems.push.apply(staticMenuItems, arguments);
};
/** #ngInject */
this.$get = function($state, layoutSizes) {
return new _factory();
function _factory() {
var isMenuCollapsed = shouldMenuBeCollapsed();
this.getMenuItems = function() {
var states = defineMenuItemStates();
var menuItems = states.filter(function(item) {
return item.level == 0;
});
menuItems.forEach(function(item) {
var children = states.filter(function(child) {
return child.level == 1 && child.name.indexOf(item.name) === 0;
});
item.subMenu = children.length ? children : null;
});
return menuItems.concat(staticMenuItems);
};
this.shouldMenuBeCollapsed = shouldMenuBeCollapsed;
this.canSidebarBeHidden = canSidebarBeHidden;
this.setMenuCollapsed = function(isCollapsed) {
isMenuCollapsed = isCollapsed;
};
// I need call this method in another controller
this.getStorage = function(){
console.log(localStorage.user);
}
this.isMenuCollapsed = function() {
return isMenuCollapsed;
};
this.toggleMenuCollapsed = function() {
isMenuCollapsed = !isMenuCollapsed;
};
this.getAllStateRefsRecursive = function(item) {
var result = [];
_iterateSubItems(item);
return result;
function _iterateSubItems(currentItem) {
currentItem.subMenu && currentItem.subMenu.forEach(function(subItem) {
subItem.stateRef && result.push(subItem.stateRef);
_iterateSubItems(subItem);
});
}
};
function defineMenuItemStates() {
return $state.get()
.filter(function(s) {
return s.sidebarMeta;
})
.map(function(s) {
var meta = s.sidebarMeta;
return {
name: s.name,
title: s.title,
level: (s.name.match(/\./g) || []).length,
order: meta.order,
icon: meta.icon,
stateRef: s.name,
};
})
.sort(function(a, b) {
return (a.level - b.level) * 100 + a.order - b.order;
});
}
function shouldMenuBeCollapsed() {
return window.innerWidth <= layoutSizes.resWidthCollapseSidebar;
}
function canSidebarBeHidden() {
return window.innerWidth <= layoutSizes.resWidthHideSidebar;
}
}
};
}
})();
This is the module I need to inject the service and call the method I need DashboardModule:
/**
* #author v.lugovsky
* created on 16.12.2015
*/
(function() {
'use strict';
angular.module('BlurAdmin.pages.dashboard', [])
.config(routeConfig);
/** #ngInject */
function routeConfig($stateProvider) {
// I need call service here
baSidebarService.getStorage()
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: 'app/pages/dashboard/dashboard.html',
title: 'Dashboard',
resolve: {
user: function(baSidebarService){
console.log('DASHBOARD',baSidebarService.getStorage())
}
},
sidebarMeta: {
icon: 'ion-android-home',
order: 0,
},
});
}
})();
Is there any way to do this? I need to get this method so I can make a logic over that value
Inject the service:
/** #ngInject */
function routeConfig($stateProvider, baSidebarService) {
// I need call service here
baSidebarService.getStorage()
Given the following test.
The $provided service is not being injected. If I debug the test in karma I can see that the service being provided is the real one, and not the mock.
The really weird thing, is that if I remove the $provide.service... I get an error Error: [$injector:unpr] Unknown provider: ficaServiceProvider <- ficaService. This clearly means that the service is getting registered, just not replaced?
describe("component: FicaStatusComponent",
function () {
var fs;
beforeEach(function () {
module("aureus",
function ($provide) {
$provide.service("ficaService", function () {
this.status = function () {
return $q(function (resolve, reject) {
resolve([{ documentType: { id: 1 } }]);
});
}
})
});
});
beforeEach(inject(function (_$componentController_, _ficaService_) {
$componentController = _$componentController_;
fs = _ficaService_;
}));
it("should expose a `fica` object", function () {
console.log('should expose');
var bindings = {};
var ctrl = $componentController("ficaStatus", null, bindings);
expect(ctrl.fica).toBeDefined();
});
it("compliant with no documents should not be compliant",
function () {
var ctrl = $componentController("ficaStatus");
expect(ctrl.fica.length).toEqual(1);
});
}
);
The second test compliant with no documents... is failing.
Chrome 56.0.2924 (Windows 10 0.0.0) component: FicaStatusComponent compliant with no documents should not be compliant FAILED
Error: Unexpected request: GET api/fica/status/
I have also tried this, expecting to have an empty object injected, but the "real" service is there nevertheless?
module("aureus", function($provide) {
$provide.value("ficaService", function() { return {}; });
$provide.service("ficaService", function() { return {}; });
});
Here is the implementation of the controller for the component:
var FicaStatusController = (function () {
function FicaStatusController($log, $loc, ficaService) {
var _this = this;
this.$log = $log;
this.$loc = $loc;
this.ficaService = ficaService;
this.fica = [];
this.ficaService.status(1234).then(function (_) { return _this.fica = _; });
}
FicaStatusController.$inject = ["$log", "$location", "IFicaStatusService"];
module("aureus").component("ficaStatus", new FicaStatusComponent());
module("aureus").service("IFicaStatusService", FicaStatusService);
The service is as follows:
var FicaStatusService = (function () {
function FicaStatusService($log, $http) {
this.$log = $log;
this.$http = $http;
}
FicaStatusService.prototype.status = function (accountNumber) {
var url = "api/fica/status/" + accountNumber;
this.$log.log("status: " + url);
return this.$http
.get(url)
.then(function (_) { return _.data; });
};
return FicaStatusService;
}());
...
You have added your service in your module like this:
module("aureus").service("IFicaStatusService", FicaStatusService);
That means that you will need to provide IFicaStatusService instead of ficaService with $provide.
I'am sloving problem of reusing same function with scope access in two Controllers
decribed here:
How to include/inject functions which use $scope into a controller in angularjs?
In controller:
new CommonService($scope).getSomethingFromDB();
In factory:
services.factory("CommonService", function (DBService) {
function Factory ($scope) {
this.$scope = $scope;
}
Factory.prototype.getSomethingFromDB = function () {
if( angular.isUndefined(this.$scope.vrsteObracuna) || this.$scope.vrsteObracuna === null) {
this.$scope.loading = true;
DBService.getSomethingFromDB(
function success(data) {
this.$scope.loading = false; //ERROR !!!
this.$scope.vrsteObracuna = data;
},
function error(data, status, headers, config) {
this.$scope.loading = false;
etna.notifications.error("Error fetching!");
}
)
}
return this.$scope.vrsteObracuna;
}
return Factory;
});
Problem is that after success callback from DBService.getSomethingFromDB
this.$scope.loading is undefined ?
You haven't $scope into "success" closure, try to use this code:
services.factory("CommonService", function (DBService) {
function Factory ($scope) {
this.$scope = $scope;
}
Factory.prototype.getSomethingFromDB = function () {
if( angular.isUndefined(this.$scope.vrsteObracuna) || this.$scope.vrsteObracuna === null) {
this.$scope.loading = true;
var that = this;
DBService.getSomethingFromDB(
function success(data) {
that.$scope.loading = false; //ERROR !!!
that.$scope.vrsteObracuna = data;
},
function error(data, status, headers, config) {
that.$scope.loading = false;
etna.notifications.error("Error fetching!");
}
)
}
return this.$scope.vrsteObracuna;
}
return Factory;
});
I have a problem with my service in angular.
My service has the next code:
app.service("Utilidades", ['$http', '$window', function ($http, $window) {
return {
Get: function (urlAbsoluta, parametros, callback) {
var Utilidades = this;
$http
.get(app.UrlBase + urlAbsoluta, parametros)
.then(function (data) {
var Datos = angular.fromJson(data);
Utilidades.GuardarToken(Datos.Token);
callback(Datos);
});
},
ObtenerMenu: function () {
var Utilidades = this;
Utilidades.Get("Administracion/Api/Usuarios/Menu", {}, function (Datos) {
Datos = angular.fromJson(Datos.data);
if (Datos.Error == "") {
return Datos.Resultado;
} else {
return "";
}
});
}
}
}]);
Then, in my controller i have the next code:
app.controller('LoginCtrl', ['$scope', '$http', '$location', 'Utilidades',
function Iniciador($scope, $http, $location, Utilidades) {
var Li = this;
Li.Usuario = "";
Li.Contrasena = "";
Li.Error = "";
Li.MenuItems = [];
Li.Menu = function () {
Li. MenuItems = Utilidades.ObtenerMenu();
}
}]
);
When i run this, Li.MenuItems have undefined value and i don't know why.
Your return statements are in a function inside your ObtenerMenu method so the ObtenerMenu method is not actually returning anything. You need to provide a way to access the resulting value:
Service
app.service("Utilidades", ['$http', '$window', function ($http, $window) {
return {
Get: function (urlAbsoluta, parametros) {
var Utilidades = this;
// v------------ return statement here
return $http
.get(app.UrlBase + urlAbsoluta, parametros)
.then(function (data) {
var Datos = angular.fromJson(data);
Utilidades.GuardarToken(Datos.Token);
// v------------ return statement here
return Datos;
});
},
ObtenerMenu: function () {
var Utilidades = this;
// v------------ return statement here
return Utilidades.Get("Administracion/Api/Usuarios/Menu", {})
.then(function (Datos) {
if (Datos.Error == "") {
return Datos.Resultado;
} else {
return "";
}
});
}
};
}]);
In Controller
Li.Menu = function () {
Utilidades.ObtenerMenu()
.then(function (resultado) {
Li. MenuItems = resultado;
});
}
It's because ObtenerMenu function is asynchronous function. This function doesn't return anything initially (so undefined) and later, after some time when ajax request finishes, this function is already finished its execution stack
I am trying to create a tag layout filled with categories, but I am not getting my Authentication because I am trying to resolve that service in my Router.
this is my Router code
(function () {
'use strict';
angular
.module('learningApp')
.config(sslRouter);
// Minification safe dependency Injection
sslRouter.$inject = ['$stateProvider'];
function sslRouter ($stateProvider) {
// SSL Route Definition
$stateProvider.state('ssl', {
parent: 'policy',
url: '/ssl',
data: {
roles: ['USER']
},
views: {
'policyConfig': {
templateUrl: 'components/configuration/service/policy/ssl/ssl.tpl.html',
controller: 'SSL'
}
},
resolve: {
'sslServiceData': function(sslService) {
return sslService.promise;
}
}
});
}
}());
This is my Service
(function() {
'use strict';
angular
.module('learningApp')
.factory('sslService', sslResource);
sslResource.$inject = ['Principal', '$resource', 'BASE_URL', 'exDomainService'];
function sslResource (Principal, $resource, BASE_URL, exDomainService) {
debugger;
var res = $resource(BASE_URL + '/api/companies/' + Principal.company() + '/sconfig/ssl/sslConfiguration', {}, {
query: {
method: 'GET',
isArray: false
},
update: {
method: 'PUT'
}
});
var data = {};
var servicePromise = _initService();
servicePromise.$promise.then(function (d) {
data = d;
if (!data.excludedCategories) {
data.excludedCategories = [];
}
if (!data.excludedDomains) {
data.excludedDomains = [];
}
exDomainService.tableData = getExcludedDomains();
});
function _initService () {
return res.query();
}
return {
promise: servicePromise,
rest: res
}
}
}());
This is my controller
(function() {
'use strict';
angular
.module('learningApp')
.controller('SSL', SSLController);
SSLController.$inject = ['$scope', 'sslService', 'preDefinedCategoryService', '$timeout', 'exDialog', 'exDomainService'];
function SSLController ($scope, sslService, preDefinedCategoryService, $timeout, exDialog, exDomainService) {
var vm = $scope;
/**
* #desc Flags for different type checks
* Booleans and Categories
*/
vm.flags = {
// By default true
enableInspectSSLTraffic: sslService.getSSlInspectionFlag(),
allowUntrustedCertificates: sslService.getUntrustedCertificatesFlag(),
allowHostnameMismatch: sslService.getHostnameMismatchFlag(),
selectedCategory: undefined,
initializing: true
};
vm.excludedCategories = sslService.getExcludedCategories();
vm.predefinedCategories = preDefinedCategoryService.rest.query();
vm.predefinedCategories.$promise.then(function() {
vm.categories = _processedCategories(vm.predefinedCategories, vm.excludedCategories);
});
}
}());
So basically problem is, I am getting Principal.Identity as undefined, but if I remove resolution from Router, I got identity but then I lose my data coming from service. I want my service to be loaded completely before its Controller, and I want my principal service to be loaded before service.
for Reference, This is my Principal Class
'use strict';
angular.module('learningApp')
.service('Principal',['$q', 'Account', 'localStorageService', function Principal($q, Account, localStorageService) {
var _identity,
_authenticated = false;
return {
isIdentityResolved: function () {
return angular.isDefined(_identity);
},
isAuthenticated: function () {
return _authenticated;
},
isInRole: function (role) {
if (!_authenticated || !_identity || !_identity.roles) {
return false;
}
return _identity.roles.indexOf(role) !== -1;
},
isInAnyRole: function (roles) {
if (!_authenticated || !_identity.roles) {
return false;
}
for (var i = 0; i < roles.length; i++) {
if (this.isInRole(roles[i])) {
return true;
}
}
return false;
},
company: function () {
debugger;
if (_identity) return _identity.companyId;
},
authenticate: function (identity) {
_identity = identity;
_authenticated = identity !== null;
},
identity: function (force) {
var deferred = $q.defer();
if (force === true) {
_identity = undefined;
}
// check and see if we have retrieved the identity data from the server.
// if we have, reuse it by immediately resolving
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
// rather than retrieving from server, use cookie or whatever method
var cookieFound = UTIL.cookie("token");
if (cookieFound) {
var response = JSON.parse(JSON.parse(cookieFound));
var expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
response.expires_at = expiredAt.getTime();
localStorageService.set('token', response);
}
// retrieve the identity data from the server, update the identity object, and then resolve.
Account.get().$promise
.then(function (account) {
account.data.roles = ["ADMIN", 'USER'];
account.data.langKey = "en";
_identity = account.data;
_authenticated = true;
deferred.resolve(_identity);
})
.catch(function() {
_identity = null;
_authenticated = false;
deferred.resolve(_identity);
});
return deferred.promise;
}
};
}]);