AngularJS factory undefined error - angularjs

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
}
});

Related

AngularJS scope variable undefined in page load for other function

Im trying to get initialize the scope variable via http get request in page load in first function but then when trying to use the scope variable in other function in the same page load, it is undefined.
app.controller('GradeAndSectionCtrl', function ($scope, $http) {
$scope.GetCategories = function () {
$http({
method: 'GET',
url: '/GradeAndSection/GetCategories'
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
}
});
};
$scope.GetGrades = function () {
\\$scope.drpCategory; here; is; undefined;
$http({
method: 'GET',
url: '/GradeAndSection/GetGrades?categoryID=' + $scope.drpCategory
}).then(function (response) {
$scope.grades = response.data;
});
};
$scope.GetCategories();
$scope.GetGrades();
});
You are making asynchronous call using promises in your code therefore $scope.drpCategory may not be loaded when you call GetGrades function. You can call your GetGrades function when GetCategories is resolved.
$scope.GetCategories = function () {
$http({
method: "GET",
url: "/GradeAndSection/GetCategories"
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
$scope.GetGrades();
}
});
}
Try to call the function GetGrades in then()
$scope.GetCategories = () => {
$http
({
method: 'GET',
url: 'categories.json',
})
.then(data => {
$scope.categories = data.data;
$scope.drpCategory = $scope.categories[0].category
$scope.GetGrades($scope.drpCategory)
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
}
$scope.GetGrades = (drpCategory) => {
$http
({
method: "GET",
url: "categories_" + drpCategory + ".json"
}).then(function (response) {
$scope.grades = response.data;
console.log($scope.grades)
});
}
$scope.GetCategories()
Working example: http://plnkr.co/edit/ZN8nI7OhAyWiJWlqeJsU?p=preview

Offload API request from controller to service

I offloaded the call to the Twitter API from my controller into a service:
angular.module('main')
.service('Tweet', function ($log, $http, Config, $ionicLoading) {
this.show = function () {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner><br>Loading'
}).then(function () {
$log.log("The loading indicator is now displayed");
});
};
this.hide = function () {
$ionicLoading.hide().then(function () {
$log.log("The loading indicator is now hidden");
});
};
var consumerKey = encodeURIComponent(Config.TWITTER.CONSUMERKEY);
var consumerSecret = encodeURIComponent(Config.TWITTER.CONSUMERSECRET);
var tokenCredentials = btoa(consumerKey + ':' + consumerSecret);
this.getToken = function () {
this.show();
return $http({
method: 'POST',
url: 'https://api.twitter.com/oauth2/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + tokenCredentials
},
data: 'grant_type=client_credentials'
})
.then(function (result) {
if (result.data && result.data.access_token) {
$http.defaults.headers.common.Authorization = 'Bearer ' + result.data.access_token;
}
})
.catch(function (error) {
console.log(error);
});
};
this.getTimeline = function () {
$log.log($http.defaults.headers.common.Authorization);
return $http({
method: 'GET',
url: 'https://api.twitter.com/1.1/search/tweets.json?q=%40postbank',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
})
.then(function (result) {
return result.data.statuses;
})
.catch(function (error) {
console.log(error);
});
};
this.analyzeResult = function (input) {
this.tweets = input;
this.hide();
};
var that = this;
this.getTweets = function () {
this.getToken()
.then(this.getTimeline)
.then(function (result) {
that.analyzeResult(result);
});
}
});
I inject the service into my main controller and call the getTweets() function:
angular.module('main')
.controller('MainCtrl', function ($log, Tweet) {
Tweet.getTweets();
});
I can see that all the promises are executed through the console, but this.tweets stays empty. How do I send the data that is coming from the service/promise to the controller?
this within service constructor is service's context, not controller's. And services shouldn't operate on the scope.
Unwrap service promise in controller:
var self = this;
Tweet.getTweets().then(function () {
self.tweets = input;
});

chrome shows the error TypeError: Cannot read property 'then' of undefined, even the promise was returned?

i have the following code for save operation:
here is my angular service: this already returns the promise
factory('customersaveService', function ($http, $q) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
var deffered = $q.defer();
$http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
.success(function (d) {
deffered.resolve(d);
})
.error(function (e) {
deffered.reject(e);
});
}
return factoryObject;
});
in here the promise is returned. therefore it shoudl not throw the error
"TypeError: Cannot read property 'then' of undefined"
the error comes from the controller's code:
$scope.SaveCustomer = function (data)
{
if ($scope.ButtonText == 'Save')
{
$scope.message = "";
$scope.submitted = true;
$scope.User = data;
console.log($scope.User);
customersaveService.SaveNewUserSrv($scope.User).then(function (d) { <=== error line
console.log('before success part');
if (d == 'success')
{
console.log('im in success part');
clearform();
}
},
function (e) {
});
}
}
why this throws the error when the promise was returned?
1.Create service like below :
2.No need of $q service.
factory('customersaveService', function ($http) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
}
return factoryObject;
});
factory('customersaveService', function ($http) {
var SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: { 'cust': data }
});
};
return {
SaveNewUserSrv: SaveNewUserSrv
};
});
And in the controller, sure you inject the service customersaveService

How to return data from Factory Angular?

How to return data from factory?
.factory('albumService', ['$http', function($http) {
return {
getAlbums: function (type) {
var request = $http({
method: "POST",
url: "/albums/getalbums",
data: $.param({ type : type }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
request.success(function (data) {
return data;
});
}
};
}])
I need return data from factory in section
request.success(function (data) {
return data;
});
That result will be in $scope.albums = albumService.getAlbums('select');
Service :
.factory('albumService', ['$http', '$q, function($http,$q) {
return {
getAlbums: function (type) {
var albumPromise = $q.defer();
$http({
method: "POST",
url: "/albums/getalbums",
data: {'type':type},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data){
return albumPromise.resolve(data);
})
.error(function(error){
return albumPromise.reject(error);
})
return albumPromise.promise;
}
};
}])
Inside yr Controller call it like this.
albumService.getAlbums('select')
.then(function(data){
$scope.albums=data;
}, function(error){
console.log('failed'+error);
})

How can I pass value store in localstorage in header of services using angularJS?

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

Resources