I am trying to create a factory that gets a token from a web api and then shares that token with multiple controllers. I've tried my best to create the factory and inject it into the controller but I am not sure if I am doing this correctly yet? I'm getting an angular 'unknown provider' error. Please advise, new to angular. Thank you.
securityApp.factory('getToken', function ($scope, $http) {
var token = "";
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: $scope.userName, password: $scope.password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function (data, status, headers, config) {
token = data.access_token;
return token;
});
});
securityApp.controller('membersController', function ($scope, $http, getToken) {
$http({ method: 'GET', url: '/api/Members/?access_token=' + getToken.token, headers: { 'Authorization': 'Bearer ' + getToken.token } })
.then(function (response) {
$scope.members = response.data;
});
});
A service can't be injected with $scope. Only controllers can. The only scope that can be injected in a service is the $rootScope. You need to pass the user name and the password to your service when calling it. It can't bet the user name and password from nowhere.
PS: when you ask about an error, post the complete and exact error message.
Your factory not return any thing (Read this). Its should be like this
securityApp.factory('getToken', function ($scope, $http) {
return {
getAccessToken: function () {
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: $scope.userName, password: $scope.password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function (data, status, headers, config) {
return data.access_token;
});
},
};
});
and call it in your controller like below.
securityApp.controller('membersController', function ($scope, $http, getToken) {
$scope.token = getToken.getAccessToken();
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.then(function (response) {
$scope.members = response.data;
});
});
Update:
To solve the error: "Error: [$injector:unpr] Unknown provider change the code
securityApp.controller('membersController', ['$scope', '$http','getToken', function ($scope, $http, getToken) {
$scope.token = getToken.getAccessToken();
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token} })
.then(function (response) {
$scope.members = response.data;
});
} ]);
Demo Sample
Related
I am using below function to loadbenefittypes.
my get data function
$scope.loadCashBenefitTypes = function (){
$http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
url: appConfig.apiUrl + "/benefit-types/income?income_type=Cash Benefit",
}).then(function (response) {
$scope.func1 = response.data
}, function (response) {
});
}
i am using above function to load benefit types in multiple locations in my application. therefore i need to reuse this function as a service. how i convert above function and how i assign it to different drop down models
To re-factor the code to a service, return the $http promise:
app.service("myService", function($http, appConfig) {
this.getCashBenefitTypes = function (){
return $http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
params: { income_type: 'Cash Benefit' },
url: appConfig.apiUrl + "/benefit-types/income",
}).then(function (response) {
return response.data;
});
}
});
Then inject that service in the controllers:
app.controller("app", function($scope, myService) {
myService.getCashBenefitTypes()
.then(function(data) {
$scope.types = data;
}).catch(response) {
console.log("ERROR", response);
});
});
For more information, see
AngularJS Developer Guide - Creating Services
I am making a post request to an api with submit() function which is attached to a ng-click directive sending the data in JSON format, it returns this error.
It is running fine on postman so the error is on client side only.
Also the email and selectedIds variables are not empty.
Here is my controller file:
app.controller('categoryController', ['$scope', '$rootScope', '$sce', '$http', '$timeout','$window', function($scope, $rootScope, $sce, $http, $timeout, $window) {
$scope.allCategories = {};
$http({
method: 'GET',
url: 'http://qubuk.com:8081/api/v1/alltag'
})
.then(function (data) {
// console.log("DATA:" + JSON.stringify(data.data.categories[0].displayName));
// console.log("DATA category:" + JSON.stringify(data.data.categories));
$scope.allCategories = data.data.categories;
});
$scope.selectedIds = [];
$scope.change = function(category, active){
if(active){
$scope.selectedIds.push(category.id);
}else{
$scope.selectedIds.splice($scope.selectedIds.indexOf(category.id), 1);
}
// console.log("SELECTED IDS:" + $scope.selectedIds);
};
$scope.email = "faiz.krm#gmail.com"
console.log("email is "+ $scope.email);
$scope.submit = function () {
var tagsData = {"emailId": $scope.email,
"tagsId": $scope.selectedIds};
console.log("tagsData:" + JSON.stringify(tagsData));
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData
})
.then(function (data) {
console.log("Ids sent successfully!");
alert("successful");
$window.location.href = '/app/#/feed';
})
};
// console.log("amm Categories:" + JSON.stringify($scope.allCategories));
}]);
edit: the response is not a JSON object... it is a string. I do think error is due to this only... how can i resolve it on the front end...
Try to add:
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
to your request:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
})
Alternately try to pass a stringify data:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: JSON.stringify(tagsData),
headers: {'Content-Type': 'application/json'}
})
I have two api one is for login and another is for logout, and on succcessfulll login I am getting the acesstoken and on the basis of acesstoken I have to logout by passing the that acesstoken in header.
So for logout what I did, I stored that acesstoken value in localstorage and pass in the header but I am getting error "AccessToken is invalid."
Here is services.js:
angular.module('server', [])
.factory('api', function($http) {
var token = localStorage.AccessToken;
console.log(token);
var server = "http://myapi-nethealth.azurewebsites.net";
return {
//Login
login : function(formdata) {
return $http({
method: 'POST',
url: server + '/Users/Login',
data: $.param(formdata),
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
});
},
logout : function() {
return $http({
method: 'POST',
url: server + '/Users/Me/Logout',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded', 'Authorization' : 'token ' + token},
/*headers: { 'Content-Type' : 'application/json', 'Authorization' : 'token ' + token},*/
}).success(function (data, status, headers, config){
alert(JSON.stringify(status));
});
}
};
});
//Controller.js..
ctrl.controller('logout', function($scope, $window, $state, api) {
$scope.logout = function() {
api.logout()
.success(function(data) {
console.log(data);
$scope.response = data;
$state.go('home');
})
.error(function(data) {
console.log(data);
$scope.response = data;
});
}
});
ctrl.controller('search', function($scope, $state) {
$scope.search = function() {
$state.go('clinic-list');
};
});
ctrl.controller('clinicCtrl', function($scope, $state, $window, api) {
$scope.formData = {};
$scope.clinicCtrl = function() {
/*$scope.loading = true;*/
api.login($scope.formData)
.success(function(data, status) {
console.log(data);
$scope.response = data;
if (data.hasOwnProperty('AccessToken') && data.AccessToken.length > 5) {
$state.go('home');
window.localStorage['AccessToken'] = angular.toJson(data.AccessToken);
var accessData = window.localStorage['AccessToken'];
console.log(accessData);
} else {
$state.go('login');
}
/*$scope.loading = false;*/
})
.error(function(data) {
console.log(data);
$scope.response = data;
$window.alert($scope.response.Message);
console.log($scope.response.Message);
});
}
});
Please tell me how can I do this....
angular.module('server', []).factory('authInterceptor',function($q,$location) {
return {
request: function(config) {
config.headers = config.headers || {};
if(localStorage.AccessToken) {
config.headers.AccessToken = localStorage.AccessToken;
}
config.headers.requestResourse = $location.$$url;
return config;
},
responseError: function(response) {
return $q.reject(response);
}
}
}).config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})..factory('api', function($http) {
var token = localStorage.AccessToken;
console.log(token);
var server = "http://myapi-nethealth.azurewebsites.net";
return {
//Login
login : function(formdata) {
return $http({
method: 'POST',
url: server + '/Users/Login',
data: $.param(formdata),
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
});
},...............
this will append the token to all the requests, after u getting the reponse, in the controller you can re set the token :)
customize according to your variables
I am stuck here, I don't know what I am missing or how to debug this further. I continue to get this error: 'updateMemberServiceFactory is undefined' when I call it from an ng-click event. Please advise. If this is a simple typo I apologize I just can't see what's wrong. I'm trying to call into a PUT method on my controller but it never gets called. New to AngularJS. Thank you.
securityApp.factory('updateMemberServiceFactory', function ($http) {
function update(memberServiceID) {
$http({ method: 'PUT', url: 'http://localhost:62791/api/MemberServices/', data: { memberServiceID: memberServiceID } })
.then(function (result) {
alert('success');
}, function (errorResponse) {
});
};
});
securityApp.controller('memberServicesController', function ($scope, $http, $routeParams, $location, getTokenFromServer, updateMemberServiceFactory) {
var id = $routeParams.memberID;
$scope.username = 'aharris1#test.com';
$scope.password = 'SuperPass1!';
getTokenFromServer.getToken($scope.username, $scope.password).then(function (data) {
$scope.token = data;
$http({ method: 'GET', url: '/api/MemberServices/' + id + '?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.success(function (response) {
$scope.memberServices = "";
$scope.memberServices = response;
$http({ method: 'GET', url: '/api/Members/' + id + '?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.success(function (response) {
$scope.member = response;
});
$http.get('/api/ServiceTypes/')
.then(function (response) {
$scope.serviceTypes = response.data;
});
});
});
$scope.updateMemberService = function () {
updateMemberServiceFactory.update( { memberServiceID: memberServiceID }, null, function () {
alert('update called');
});
};
});
<i class="fa fa-save"></i>
When you use someApp.factory(someFunction) the some someFunction should return an object that will be injected when needed.
In your case:
securityApp.factory('updateMemberServiceFactory', function ($http) {
function update(memberServiceID) {
$http({ method: 'PUT', url: 'http://localhost:62791/api/MemberServices/', data: { memberServiceID: memberServiceID } })
.then(function (result) {
alert('success');
}, function (errorResponse) {
});
};
return { // <---- this object will get injected, when required
update : update
}
});
I am trying to create a factory that will return a token to the controller. This code only works as far as getting the token from the server but does not pass the token back into the controller. The token just comes back empty inside the controller. Please advise. Thank you.
securityApp.factory("getTokenFromServer", function ($http, $q) {
var token;
function getToken(userName, password) {
var deferred = $q.defer();
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (data) {
token = data.access_token;
deferred.resolve(token);
});
return deferred.promise;
}
return {
getToken: getToken
};
});
securityApp.controller('membersController', function ($scope, $http, getTokenFromServer) {
$scope.username = 'aharris1#test.com';
$scope.password = 'SuperPass1!';
getTokenFromServer.getToken($scope.username, $scope.password).then(function (data) {
$scope.token = data;
alert($scope.token);
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.then(function (response) {
$scope.members = response.data;
});
});
});
That is because you are not accessing the data in the right way. When using then chain of the promise the result is a combination of data, status etc.. (when opposed to success call back which breaks up pieces and give you data right up as the first argument) So i believe you should look for result.data.access_token instead of result.access_token
.then(function (result) {
token = result.data.access_token;
deferred.resolve(token);
});
And with you have you can just simplify your api method to return http promise itself rather creating a defered object:-
securityApp.factory("getTokenFromServer", function ($http, $q) {
function getToken(userName, password) {
return $http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (result) {
return result.data.access_token; //Return the data
}, function(errorResponse) {
return $q.reject(errorResponse.data);//Reject or return
});
}
return {
getToken: getToken
};
});