AngularJS scope variable undefined in page load for other function - angularjs

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

Related

Angular $http Respose Data is Undefined

I am trying to access an xml file from the server.
When I check in using code inspector the value of response.data is all set.
But the returned data is not reaching the controller.
In the controller. response.data is undefined.
fuseApp.factory('fuseHttpRequest', ['$http', function ($http) {
var getRequest = function () {
var xml;
xml = $http({
method: 'GET',
url: 'http://vlandproperties.com/apitest/orders.xml',
headers: {
'Content-Type': 'application/xml'
},
timeout: 10000,
transformResponse: function (data) {
return data;
}
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
return response.data
});
};
return {
getRequest: getRequest
};
}]);
console.log output

How to use callback in $http Angular JS?

I have an service with methods that does requests to server:
this.add = function (data, cb) {
$http({
method: 'POST',
url: path
}).then(function successCallback(response) {
cb(response);
}, function errorCallback(response) {
// TODO
});
};
When I call add() as:
genresService.add(function (data) {
// TODO
});
I get error:
TypeError: cb is not a function
at successCallback (custom.js:329)
on line:
cb(response);
this.add = function (data, callback,error) {
$http({
method: 'POST',
url: path,
data: data
}).then(callback).catch(error);
};
//then call like this
genresService.add(myData ,function (res) {
console.log(res);
}
,function(errorResponse){
console.log(errorResponse);
});
You need to pass two params in your add function - first is data and other is callback function. You are only passing one. You need to pass two arguments like this,
genresService.add( data, function (data) {
// TODO
});
The 'add' function expects 2 parameters : data & a callback :
genresService.add(data,function (response) {
// TODO use response.data I presume
});
Maybe you want to do:
this.add = function (dataToPost, cb) {
$http.post(path,dataToPost)
.then(function successCallback(response) {
cb(response.data);
}, function errorCallback(response) {
// TODO
});
};
genresService.add(someData,function (data) {
// TODO use data I presume
});
this.add = function (jsonobj, callback) {
$http({
method: 'POST',
url: path,
data: jsonobj
}).then(function(res) {
callback(res);
}, function(err) {
callback(err)
});
};
//missing data like up : i call it jsonobj and finction got res is a callback
genresService.add(jsonobj ,function (res) {
console.log(res);
}
try it

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

AngularJS factory undefined error

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

Resources