angular ionic $http service not working - angularjs

Loading json using $http isn't working. Can't figure out where the problem is
.factory('streamStore', function ($http) {
var cachedData = null;
return {
findAll: function getAll() {
$http.get('img/sample.json').
success(function (data, status, headers, config) {
console.log("inside stream controller");
cachedData = data; return cachedData;
}).
error(function (data, status, headers, config) {
// log error
});
}
And in my controller this is how I'm calling it:
.controller('streamCtrl', function ($scope, ,streamStore) {
$scope.streams = streamStore.findAll();//not working ,

There is a error in your code . Check below
.factory('streamStore', function ($http) {
var cachedData = null;
return {
findAll: function() {
$http.get('img/sample.json').
success(function (data, status, headers, config) {
console.log("inside stream controller");
cachedData = data;
return cachedData;
}).
error(function (data, status, headers, config) {
// log error
});
}
and then call , as you were calling in your controller.
or use this
.factory('streamStore', function ($http) {
var cachedData = function(){
return $http.get('img/sample.json');
};
return {
findAll: function(){
return cachedData();
}
}
});
then in controller
streamStore.findAll().then(function(response){
console.log(response) // here is your data
})

since you have not returned anything from factory.
.factory('streamStore', function ($http) {
var cachedData = null;
return {
findAll: function getAll() {
$http.get('img/sample.json').
success(function (data, status, headers, config) {
console.log("inside stream controller");
cachedData = data; return cachedData;
// should return something
return cachedData
}).
error(function (data, status, headers, config) {
// log error
});
}
one more suggestion return promise to make it safe .
return $http.get('img/sample.json')...
and handle with then in controller.
.controller('streamCtrl', function ($scope, ,streamStore) {
streamStore.findAll().then(function(res){
//res will contain your data
$scope.streams = res.data;
});

Related

Using AngularJs how to write code for Sucess and Failure

How to apply Success And Failed in AngularCtrl
$scope.Btncall = function () {
var xx = MyService.GetDatafromApi();
xx.then(function (d) {
$scope.Employee = d.data;
}
),success(function (success) {
alert('ok');
})
What i understood is that you're asking how to handle a promise return success/fail like the one you get from the $http request service, so here's below an example:
$http.get('http://freegeoip.net/json')
.success(function (data, status, headers, config) {
//TODO When request Success
console.log(data);
$scope.Employee = data;
})
.error(function (data, status, headers, config) {
//TODO When request Failed
console.log(data); //Server Response values if there's any
$scope.Employee = [];
});
This is a sample code which helps you.
$scope.Btncall = function () {
MyService.GetDatafromApi().success(function (data, status,headers)
{
$scope.Employee = data;
})
.error(function (data, status, headers) {
$scope.Employee = [];
});
}
//Call Btncall Function..
$scope.Btncall();

deferred.resolve giving error TypeError: undefined is not a function

I am using angularjs and cordova tool for creating application.
I have created service, which contains code for calling APIs. and in that I want to return response to my angular controller.
My code is,
Service,
JodoModule.factory('commonServices', function ($http, $q, $rootScope) {
return {
getServiceData: function (url) {
$rootScope.loading = true;
var deferred = $q.defer();
var req = {
method: 'GET',
url: url
}
$http(req).success(function (data) {
alert("data in service = " + JSON.stringify(data.Data));
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
My controller is,
commonServices.getServiceData("My url").
success(function (data, status, headers, config) {
alert(data);
}).
error(function (data, status, headers, config) {
alert("Got error");
});
In above code, in service, its showing elert message for JSON.stringify(data.Data)); in success block, so data is comming, but its not executing deferred.resolve(data); properly...
in Web tool bar its giving me error,
ie. TypeError: undefined is not a function
My o/p is :
{"status":"SUCCESS","Message":"success","Token":"","Data":[{"Id":17,"UserId":"477f1919-6b80-4804-a325-ac0cb05bcd3e","UserName":"honey","FirstName":"honey","LastName":null,"ProfilePic":false,"Status":2}]}
How can I solve this error. ?
Ordinary $q promises don't have a .success() or .error() method, but you shouldn't be using the deferred antipattern anyway. Instead, do this:
JodoModule.factory('commonServices', function ($http, $rootScope) {
return {
getServiceData: function (url) {
$rootScope.loading = true;
var req = {
method: 'GET',
url: url
};
return $http(req).then(function (result) {
alert("data in service = " + JSON.stringify(result.data.Data));
return result.data;
});
}
};
});
Controller:
commonServices.getServiceData("My url").
then(function (data) {
alert(data);
}).
catch(function (result) {
alert("Got error");
});
Quite a bit cleaner, ay?

get the value of $scope.data in a variable in same controlled

My code is some thing
$scope.data = {};
var init = function () {
$http.post('views/Report.aspx/GetMailReport', {})
.success(function (data, status, headers, config) {
$scope.data = JSON.parse(data.d);
})
.error(function (data, status, headers, config) {
$scope.data = status;
})
};
init();
var data = $scope.data;
But the var data is returning empty {}
If you want a copy you should do as below... As the http call is asynchronous you assign inside the success callback method
$scope.data = {};
var data;
var init = function () {
$http.post('views/Report.aspx/GetMailReport', {}) .success(function (data, status, headers, config) {
$scope.data = JSON.parse(data.d);
data = $scope.data;
}) .error(function (data, status, headers, config) {
$scope.data = status;
}) };
init();
Edited:
Here is the link to a fiddle that I have created.

How can I make a function call depend on completion of two $http calls in AngularJS?

In my controller I have the following calls:
optionService.init($scope);
optionService.getSubjects1($scope);
optionService.getSubjects2($scope);
optionService.getAbc($scope);
Here's the code for the optionService:
angular.module('common')
.factory('optionService',
['$http',function ($http) {
var factory = {
init: function ($scope) {
$scope.option = {};
},
getSubjects1: function ($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
getSubjects2: function ($scope) {
var url = '/api/Subject2/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects2 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
}
return factory;
}]);
Is there a way that I could make the call to optionService.getAbc depend on the completion of both the getSubjects1 and getSubjects2 calls? I will also soon be using Angular 1.2 if this makes any difference.
$q.all(promises) lets you combine multiple promises in to one:
optionService.getAbc = function($scope) {
$q.all([
optionService.getSubjects1($scope),
optionService.getSubjects2($scope)
])
.then(function() {
//...
});
}
Edit. Yes, you need to return promises from your getSubjects functions. To keep code changes to bare minimum, you could do something like this:
optionService.getSubjects1($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
return $http.get(url)
.then(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
}, function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
}
With $http.then() you create a new promise that can be combined with other promises in getAbc()
You should rewrite your getSubject1 and getSubject2 to return promise. Also passing the $scope to the method and updating the scope from the service method is not a good way of doing things. You service methods should return data which assignable in your code. This makes your services more usable and readable.
If you change getSubject1 and getSubject2 in lines of
getSubjects1: function () {
var url = '/api/Subject1/GetSelect';
return $http.get(url);
}
In your controller you can do
$q.all([
optionService.getSubjects1(),
optionService.getSubjects2()
])
.then(function([data1, data2]) {
//use data1 to update scope for subject1
// use data2 to update scope for subject2
//call any service method.
});

AngularJS $http is not defined

I'm pretty new to with AngularJS. When I'm calling $http.get I get a $http is not defined error.
This is the content of my Module:
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.
when('/view1',
{
controller: 'SimpleController',
templateUrl: 'View1.html'
}).
when('/view2',
{
controller: 'SimpleController',
templateUrl: 'View2.html'
})
.otherwise({ redirectTo: '/view1' });
});
demoApp.factory('simpleFactory', function () {
var factory = {};
factory.getAnnounces = function ($http) {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
};
return factory;
});
demoApp.controller('SimpleController', function ($scope,simpleFactory) {
$scope.announces = [];
init();
function init()
{
$scope.announces= simpleFactory.getAnnounces();
}
});
What am I missing here? Cheers.
You need to review your code as follows:
demoApp.factory('simpleFactory', ['$http', function ($http) {
return {
getAnnounces: function () {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
}
};
}]);
There's no need to pass the $http variable in the getAnnounces method definition, because it is defined already in the scope of the factory function.
I am using parameter aliasing for AngularJS in order to avoid issues with minifiers, see 'A note on minification' on the AngularJS web site.
Note anyway that $http.post.success and $http.post.error are asynchronous and you won't be able to get the data unless you're using promises ($q), see here. Therefore you could change the code this way:
demoApp.factory('simpleFactory', ['$http', '$q', function ($http, $q) {
return {
getAnnounces: function () {
var deferred = $q.defer();
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}
};
}]);
And in the SimpleController:
demoApp.controller('SimpleController', ['simpleFactory', '$scope', function (simpleFactory, $scope) {
$scope.announces = [];
simpleFactory.getAnnounces()
.then(function(data) {
// call was successful
$scope.announces = data;
}, function(data) {
// call returned an error
$scope.announces = data;
});
}]);

Resources