Jeremy Miller Jeremy Miller - 1 month ago 9
AngularJS Question

Why are $scope and var variables undefined within my angular controller , as success seems to just hide values

I make a few different

$http
calls and I want to set either variable (var blah) or $scope to be set to an object value and persist at least down a few lines so that it can be sent to a 2nd
$http
request

I get
undefined
, why and how to fix / persist the variable or scope?

app.controller('detailController', function ($scope, $interval, $http, $routeParams, $window, sessionVariables, $httpParamSerializer) {

//$scope.xid = 1; // this seems to persist but NOT if i try update it in 1st $http.get

$http.get('/Umbraco/Api/ClientsApi/GetClient/' + clientId).
success(function (data, status, headers, config) {
console.log(data); // correctly shows me object of data
$scope.xid = data.Id; // DOES NOT WORK OUTSIDE OF this $http.get
console.log(data.Id); // yes shows data inside here
//console.log(data.IsSampleData); // contains data
$scope.client = data; // this is how is then use client object in view template

}).
error(function (data, status, headers, config) {
// log error
});


This is the problem, $scope.xid does is saying undefined

console.log('before');
console.log($scope.xid);
console.log('after');


Of which this 2nd $http.get call I want to append the xid onto the end of it

$http.get('/Umbraco/Api/ActivityApi/GetActivity').
success(function (data, status, headers, config) {

$scope.activity = data; // correctly gets data

}).
error(function (data, status, headers, config) {
// log error
});


Update : FULL CODE

app.controller('detailController', function ($scope, $interval, $http, $routeParams, $window, sessionVariables, $httpParamSerializer) {

var clientId = $routeParams.id;
//console.log(clientId);

//$scope.xid = 1;

$http.get('/Umbraco/Api/ClientsApi/GetClient/' + clientId).
success(function (data, status, headers, config) {
console.log(data);

//console.log(data.Id);
//console.log(data.IsSampleData);
$scope.client = data;

}).
error(function (data, status, headers, config) {
// log error
});

console.log('before');
console.log(client.Id);
console.log('after');

$http.get('/Umbraco/Api/ActivityApi/GetActivity').
success(function (data, status, headers, config) {
//console.log(data);
//console.log(data.IsSampleData);
$scope.activity = data;

}).
error(function (data, status, headers, config) {
// log error
});


});

Answer

Use Promises and chaining

var firstRequest = $http.get(url).then(function (result) {
  /* optional - do something with result, pass through to next .then() */
  return result;
});

var secondRequest = firstRequest.then(function (result) {
  return $http.get(otherUrl);
});

var thirdREquest = secondRequest.then(function () {
  /* and so on */
});