I'm trying to access factory service within controller to obtain correct data.
Related controller code looks like:
myApp.controller('RegistrationController', ['$scope','$routeParams','$rootScope','$location','$filter','$mdDialog','checkAttendee', function($scope, $routeParams, $rootScope, $location, $filter, $mdDialog,checkAttendee){
...
$scope.addAttendee = function(ev) {
$mdDialog.show({
controller: AddDialogCntrl,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: 'ctrl',
fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
locals: {parent: $scope}
})
.then(
function(response){
if(angular.isDefined(response)){
attendees.push(response);
checkAttendee.getAttendeeInfo(response);
}
},
function(){
//no changes
}
)
.catch(
function(error) {
console.log('Error: ' + error);
}
)
};
and factory service code
myApp.factory('checkAttendee', ['$http', function($http) {
this.getAttendeeInfo = function(req) {
return $http.get("/check/attendee/", {params:{"firstName":req.firstName, "lastName":req.lastName, "email": req.email, "eventID": req.eventID}})
.then(function(response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log('Data: ' + data);
console.log('Status: ' + status);
return data;
})
.catch(function(response) {
console.log('something worng');
});
}
}]);
but that combination gives me an error Provider 'checkAttendee' must return a value from $get factory method. when there is a return value.
Any thoughts?
Option 1
When we work with factories the structure should be:
myApp.factory('checkAttendee', ['$http', function($http) {
var factory = {
getAttendeeInfo : function () {
return $http.get(/**/).then(function(response) {
// ..
return data;
}
}
}
return factory;
}]);
DEMO 1
Option 2
you can change factory to service and everything should work. A.e.:
myApp.service('checkAttendee', ['$http', function($http) {
this.getAttendeeInfo = function(req) {
return $http.get("/check/attendee/", {params:{"firstName":req.firstName, "lastName":req.lastName, "email": req.email, "eventID": req.eventID}})
.then(function(response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log('Data: ' + data);
console.log('Status: ' + status);
return data;
})
.catch(function(response) {
console.log('something worng');
throw response;
});
}
}]);
DEMO 2
Keep in mind that service extends the factory
Related
I want to load two APIs before page is going to load For it i have used the following code in $stateProvider
.state('admin-panel.default.jobadd', {
url: '/jobadd/:jobID',
templateUrl: 'app/search/jobadd.tmpl.html',
controller: 'JobaddController',
resolve: {
jobAdd: ['Search', '$stateParams','$q', function(Search,$stateParams,$q) { //Search is service
var jobAdd = Search.jobAdd($stateParams.jobID);
var isApplied = Search.is_job_applied($stateParams.jobID);
jobAdd.$promise.then(function(response) {console.log('Resource 1 data loaded!')});
isApplied.$promise.then(function(response) {console.log('Resource 2 data loaded!')});
return $q.all([jobAdd.$promise, isApplied.$promise]);
}]
},
data: {
requireLogin: true
}
});
})
But it's not give the data when injects to the controller, page seems as blank
my controller code is
.controller('JobaddController', function ($scope, $mdDialog, $state, jobAdd, Profile) {
$scope.jobs = jobAdd[0];
$scope.benifits = jobAdd[0].benifits;
if($scope.jobs.short_listed == 1)
$scope.jobs.flag = true;
else
$scope.jobs.flag = false;
$scope.checkShortList= function(job){
if(job.flag){
Profile.rmShortList(job.short_list_id);
job.flag = false;
}
else{
if(job.short_list_id === null){
Profile.addNewShortList(job.id).then(function(response){
job.short_list_id = response.short_list_id;
});
}
else
Profile.addShortList(job.short_list_id,job.id);
job.flag = true;
}
};
$scope.companyModal = function(ev) {
$mdDialog.show({
controller: 'CompanyDetailsController',
templateUrl: 'app/search/company-details.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
$scope.applyModal = function(ev) {
$mdDialog.show({
controller: 'ApplyController',
templateUrl: 'app/search/apply.tmpl.html',
locals: { Jobid: $scope.jobs.id },
parent: angular.element(document.body),
targetEvent: ev,
resolve: {
shortProfile: ['Profile', function(Profile) {
return Profile.shortProfile();
}]
},
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
var container = angular.element(document.getElementById('container'));
var section2 = angular.element(document.getElementById('section-2'));
$scope.toTheTop = function() {
container.scrollTop(0, 5000);
};
$scope.toSection2 = function() {
container.scrollTo(section2, 0, 1000);
};
})
in service code
.service('Search', [ '$http', '$q', 'API',
function($http, $q, API) {
var data = '';
this.jobAdd = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'get_job_add_detail?job_id=' + job_id,
method: "GET"
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
this.isJobApplied = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'is_job_applied?job_id='+job_id,
method: "GET",
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
}]);
What's the wrong here?? how to attach more than on service in $state resolve?
simply you can for more than one service.
resolve: {
jobAdd: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.jobAdd($stateParams.jobID);
}],
isApplied: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.isJobApplied($stateParams.jobID);
}]
}
I'm approaching AngularJS and I want to get data from a database. I succeeded in doing this
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, $http) {
$http.get("backListaUtenti.php").success(function(data) { $scope.utenti=data } )
});
but I'd like to use a factory / service in order use the data from multiple controllers (but is not working)
angular.module("myApp")
.factory("utentiService", function($http,$q) {
var self = $q.defer();
$http.get("backListaUtenti.php")
.success(function(data){
self.resolve(data);
})
.error(function(){
alert("Error retrieving data!");
})
return self.promise;
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
$scope.utente = filterFilter(utentiService.utenti, { id: userId })[0];
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
$scope.utenti = utentiService.utenti;
});
Where am I failing?
The problem is in your service implementation. Here is your code refactored:
angular.module("myApp")
.factory("utentiService", function($http) {
return {
getData: function () {
return $http.get("backListaUtenti.php").then(function (response) {
return response.data;
});
}
};
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
utentiService.getData().then(function(data) {
$scope.utente = filterFilter(data, { id: userId })[0];
});
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
utentiService.getData().then(function (data) {
$scope.utenti = data;
});
});
If your data is static you can cache the request and avoid unnecessary requests like this:
$http.get("backListaUtenti.php", { cache: true });
I am trying to follow this tutorial
http://www.codeproject.com/Articles/784106/AngularJS-Token-Authentication-using-ASP-NET-Web-A
I don't know which angularjs package to download so that I could use localStorageService and ngAuthSettings in my angularjs code.
I am getting the following err when I run the mvc 5 asp.net vs2013 web api app.
Unknown provider: localStorageServiceProvider <- localStorageService <- authInterceptorService <- $http <- $templateRequest <- $compile
Here is my code.
var appointmentReminderApp = angular.module('appointmentReminderApp', ["ngRoute", "ui.bootstrap"]);
appointmentReminderApp.config(function ($routeProvider, $locationProvider,$httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
$locationProvider.html5Mode(true);
$routeProvider
.when("/home", {
templateUrl: "App/Home.html",
controller: "HomeController"
})
.when("/Register", {
templateUrl: "App/AuthForm/templates/register.html",
controller: "authRegisterController"
})
.when("/Login", {
templateUrl: "App/AuthForm/templates/login.html",
controller: "authLoginController"
})
.otherwise({ redirectTo: "/home" });
});
appointmentReminderApp.factory('authInterceptorService', ['$q', '$injector', '$location', 'localStorageService', function ($q, $injector, $location, localStorageService) {
var authInterceptorServiceFactory = {};
var _request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('authorizationData');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
}
var _responseError = function (rejection) {
if (rejection.status === 401) {
var authService = $injector.get('authService');
var authData = localStorageService.get('authorizationData');
if (authData) {
if (authData.useRefreshTokens) {
$location.path('/refresh');
return $q.reject(rejection);
}
}
authService.logOut();
$location.path('/login');
}
return $q.reject(rejection);
}
authInterceptorServiceFactory.request = _request;
authInterceptorServiceFactory.responseError = _responseError;
return authInterceptorServiceFactory;
}]);
appointmentReminderApp.factory('authService', ['$http', '$q', 'localStorageService', 'ngAuthSettings', function ($http, $q, localStorageService, ngAuthSettings) {
var registerUser = function (auth) {
return $http.post("/api/Account/Register", auth);
};
var loginUser = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.Password;
if (loginData.useRefreshTokens) {
data = data + "&client_id=" + ngAuthSettings.clientId;
}
var deferred = $q.defer();
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
if (loginData.useRefreshTokens) {
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName, refreshToken: response.refresh_token, useRefreshTokens: true });
}
else {
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName, refreshToken: "", useRefreshTokens: false });
}
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
_authentication.useRefreshTokens = loginData.useRefreshTokens;
deferred.resolve(response);
}).error(function (err, status) {
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
return {
registerUser: registerUser,
loginUser: loginUser
};
}
]);
Have you downloaded the angular local storage service module? do you have this line
<script src="scripts/angular-local-storage.min.js"></script>
in your index.html?
The required JS file doen't come bundled with Angular.
You can get it from here.
I was unable to find the CDN, will update if I find one.
I have a service that looks like:
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({
url: '/api/v1/peers',
method: 'GET'
});
};
}
]);
In my controller, I have:
myApp.controller('PeerComparisonController', [
'$scope', '$rootScope', 'peerService', function($scope, $rootScope, peerService) {
$scope.init = function() {
$rootScope.pageTitle = 'Peer Comparison';
return $scope.peers = [];
};
$scope.getPeers = function() {
return peerService.getPeers().then(function(response) {
console.log(response);
return $scope.peers = response.data;
});
};
return $scope.init();
}
]);
My view has {{ peers }} in it. This does not get updated when the service returns. I've tried:
peerService.getPeers().then(function(response) {
return $scope.$apply(function() {
return $scope.peers = response.data;
});
});
And that also doesn't work. So any ideas?
you try something like this
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({method: 'GET', url:'/api/v1/peers'}).
then(function(response) {
return response.data;
});
};
}
]);
or
myApp.service('peerService', ['$http', function ($http) {
this.getPeers = function () {
var deferred = $q.defer();
$http({ method: 'GET', url: '/api/v1/peers' }).
then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
};
}
]);
I have this code where two controllers are using a shared service to communicate.
var app = angular.module('AdminApp', ['ngRoute']);
app.factory('SharedService', function ($rootScope) {
var sharedService = {
userId: [],
BroadcastUserId: function (id) {
this.userId.push(id);
$rootScope.$broadcast('handleBroadcast');
}
};
return sharedService;
});
app.config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: "adminLogin.html"
});
$routeProvider.when('/main', {
templateUrl: 'adminMain.html'
});
$routeProvider.otherwise({
redirectTo: '/login'
});
});
app.controller('authCtrl', function ($scope, $http, $location, SharedService) {
$scope.Userid = '';
$scope.authenticate = function (user, pass) {
$http.post('http://localhost/NancyAPI/auth', {
UserName: user,
Password: pass
}).success(function (data) {
$scope.$broadcast('Token', data.Token);
$http.defaults.headers.common['Authorization'] = 'Token ' + data.Token;
$scope.Userid = data.UserId;
SharedService.BroadcastUserId($scope.Userid);
$location.path("/main");
}).error(function (response) {
$scope.authenticationError = response.error || response;
});
};
$scope.$on('handleBroadcast', function () {
console.log('on');
});
}).$inject = ['$scope', '$rootScope', 'SharedService'];
app.controller('mainCtrl', function ($scope, $http, $q, SharedService) {
$scope.tests = [];
$scope.userId = -1;
$scope.getTests = function () {
var deferred = $q.defer();
$http.get('http://localhost/NancyAPI/auth/tests/' + $scope.userId).
success(function (data) {
deferred.resolve(data);
$scope.tests = angular.fromJson(data);
}).error(function (response) {
});
};
// THIS IS NOT FIRING
$scope.$on('handleBroadcast', function () {
$scope.userId = SharedService.userId;
});
}).$inject = ['$scope', '$rootScope', 'SharedService'];
For some reason the $scope.$on is firing in the AuthCtrl controller but not in the mainCtrl.
// THIS IS NOT FIRING
$scope.$on('handleBroadcast', function () {
$scope.userId = SharedService.userId;
});
Why is this happening and how do I fix it?
I made a subtle mistake of not providing the {$rootScope} as dependency. Once I corrected that, it worked for me. I used Inline Array Annotation mechanism to achieve the same.