Angular.js service factory $http.get not calling my service - javascript

I am trying to get data in service factory. Nothings happen.It executed code. But nothings happened. Dont know why?
Here is my service code:
'use strict';
app.factory('accountService', function($http, $location, $rootScope) {
return {
accounts: function() {
$http.get('http://localhost:29045/AccountOperation.svc/GetAccounts').success(function(data, status, headers, config) {
console.log(status);
var $promise = data;
console.log(data);
}).error(function(data, status, headers, config) {
});
}
}
});
Here is my controller(calling factory from here):
'use strict';
app.controller('accountController', function($scope, accountService, $rootScope) {
$scope.accounts = function() {
accountService.accounts();
}
});
Also i didnt get error.

On your account function you are not creating a promise or returning anything. Try:
app.factory('accountService', function($http, $location, $rootScope) {
return {
accounts: function() {
return $http.get('http://localhost:29045/AccountOperation.svc/GetAccounts');
}
}
});
This returns the promise and you can handle it anywhere you call the acccount function or you could create a promise inside the function and return it. then inside the success or error methods resolve or reject it.

I think you have to return your promise from the factory. Look at the following post under "Promises and Services"
http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/

Related

Angular service causing an error

I'm trying to receive data using $http as a dependency injection, then assign that data to a promise using angular's $q service. I'm doing something wrong.. can't seem to locate where.
Service:
myApp.factory('githubApi', ['$http', '$q',
function($http, $q) {
var deferred = $q.defer();
//Declaring a promise that will or will not return a users github information.
this.accountInformation = function (){
return $http.get('https://api.github.com/users/joshspears3')
.then(function(response){
deferred.resolve(response);
return deferred.promise;
}, function(response){
deferred.reject(response);
return deferred.promise;
})
}
}
]);
Controller:
myApp.controller('githubCtrl', [ 'githubApi', '$q', '$scope',
function(githubApi, $q, $scope){
githubApi.accountInformation()
.then(
function (result) {
$scope.data = result;
}, function (error) {
// handle errors here
console.log(error.statusText);
}
);
}
]);
Directive:
myApp.directive('githubRequest', [
function() {
return {
scope: {},
restrict: 'E',
controller: 'githubCtrl',
templateUrl: 'public/views/partials/github-request.html'
}
}
]);
Partial (github-request.html):
<p class="component-example-header">Creating a service. Making a $http request to grab my personal Github information.</p>
<div class="service-message">
<p>Avatar:</p>
<img width="20%" src="{{data.avatar_url}}" alt="" />
<p>Username: <span ng-bind="data.login"></span></p>
<p>Followers: <span ng-bind="data.followers"></span>, Following: <span ng-bind="data.following"></span></p>
</div>
<hr>
This is the error that the browser is throwing:
Error: [$injector:undef] http://errors.angularjs.org/1.4.4/$injector/undef?p0=githubApi
at Error (native)
at http://localhost:9999/bower_components/angular/angular.min.js:6:416
at Object.$get (http://localhost:9999/bower_components/angular/angular.min.js:37:32)
at Object.e [as invoke] (http://localhost:9999/bower_components/angular/angular.min.js:39:96)
at http://localhost:9999/bower_components/angular/angular.min.js:40:410
at d (http://localhost:9999/bower_components/angular/angular.min.js:38:308)
at Object.e [as invoke] (http://localhost:9999/bower_components/angular/angular.min.js:39:64)
at Q.instance (http://localhost:9999/bower_components/angular/angular.min.js:80:151)
at K (http://localhost:9999/bower_components/angular/angular.min.js:61:140)
at http://localhost:9999/bower_components/angular/angular.min.js:68:475
It's saying that my githubApi service is undefined when I inject it into my dependencies for possibly my controller?
I think it's because your factory isn't returning anything
myApp.factory('githubApi', ['$http', '$q',
function($http, $q) {
return {
accountInformation: function (){
var deferred = $q.defer();
$http.get('https://api.github.com/users/joshspears3')
.then(function(response){
deferred.resolve(response);
}, function(response){
deferred.reject(response);
})
return deferred.promise;
}
}
}
]);
is how I usually have mine
You should be returning the promise in your service method instead, and the deferred object should be inside the method, also, the service should return an object:
myApp.factory('githubApi', ['$http', '$q',
function($http, $q) {
//Declaring a promise that will or will not return a users github information.
return {
accountInformation: function () {
var deferred = $q.defer();
$http.get('https://api.github.com/users/joshspears3')
.then(function(response){
deferred.resolve(response);
}, function(response){
deferred.reject(response);
});
return deferred.promise;
}
}
}
]);
You can also simplify this as the $http service already returns a promise:
myApp.factory('githubApi', ['$http',
function($http) {
//Declaring a promise that will or will not return a users github information.
return {
accountInformation: function () {
return $http.get('https://api.github.com/users/joshspears3');
}
}
}
]);
First, $http.get returns a $q promise already, there is no need to wrap it in a promise again.
Second, a factory creates a single instance of a service which is shared. Therefore the method for the factory should return that object. Assigning anything to this within the factory function itself will not expose that method / property:
myApp.factory('githubApi', ['$http', function ($http) {
var githubApi = {
accountInformation: function () {
return $http.get('https://api.github.com/users/joshspears3');
}
};
return githubApi;
}

proper way to call http (RESTFUL WebAPI) in angularjs

I have following controller code
module.registerController('DemoCtrl', function ($scope, myFactory) {
myFactory.get(function (data) {
console.log(data); /// data is always undefined
});
});
and following the factory which is calling restful webapi
module.registerFactory('myFactory', ['$http',
function ($http) {
function get(callback) {
$http.get('mywebapiurl')
.success(function (response) {
//debugger; data comes back from server
callback(response);
}).error(function (response, status, headers, config) {
callback(response);
});
}
return {
get: get
}
}]);
The factory is calling webapi service and does gets the data back. However in controller the data doesnt get returned.
Am I missing something obvious here? Also not sure if this is the best way to call webservice in angularjs in controller using factory. Any inputs are most welcome.
Thanks,
You want to return a promise instead of passing a callback. As $http.get already returns a promise, you can just return that, or a derived promise that returns the response data directly. By the way, your factory looks like it should be a service instead:
angular.moudule('yourApp')
.service('myService', ['$http', myService]);
function myService($http) {
this.get = function(url) {
return $http.get(url)
.then(function transformData(response){
return response.data;
}).catch(function onError(rejectionResponse){
//Whatever you want to do here
});
}
}
This way myService.get will return a promise you can .then(), .catch() and .finally() on what you want, staying in the frameworks coding style. For example:
var squirrels = [];
myService.get('http://squirrelshop.com/api/squirrels')
.then(function(squirrelsData){
console.log('Got the squirrels!');
squirrels = squirrelsData;
}).catch(function(rejection){
console.warn('Couldnt fetch squirrels. Reason: ' + rejection);
});
controller code
module.registerController('DemoCtrl', function ($scope, myFactory) {
myFactory.get("url").then(function(d) {
console.log(d.data);
}
});
});
factory which is calling restful webapi
module.registerFactory('myFactory', ['$http',
function ($http) {
var apiFactory = {
get:function(url){
return $http.get(url);
}
}
return apiFactory;
}]);
Success and failure in factory
module.registerFactory('myFactory', ['$http',
function ($http) {
var apiFactory = {
get:function(url){
return $http.get(url).then(function(response){
// success
return responce.data;
},function(error){
//failure
return error;
};
}
}
return apiFactory;
}]);

How to use a service with Http request in Angular JS

I'm using AngularJS to build my web application, I've been always using controllers to make HTTP request, which makes things easier and clear for me.
But for a better code structure, and better execution for my application, I wanted to use services instead of controllers to use the web service.
I tried to make :
var app = angular.module('ofcservices', []);
app.factory('news', ['$http', function ($http) {
var news={};
news.getnews= function () {
return $http.get('http://int.footballclub.orange.com/ofc/news?offset=0&limit=5');
};
return news;
}]);
and the code of the controller :
.controller('news', function($scope, ofcservices) {
$scope.news = ofcservices.getnews();
})
Everything seems to be right ?
ofcservices.getnews() is a promise You need manage with the function sucess and error
ofcservices.getnews().
success(function(data) {
$scope.news=data
}).
error(function(data, status, headers, config) {
//show a error
});
As weel change app.factory('news' to app.factory('newsFactory' and call it in controller('news', function($scope, newsFactory) {
You can get more data about promise in the angular documentation
The concept is more or less right, but you should use the callback functions to handle the $http response correctly.
But your controller and service have the same name news, which is BAD :-) and you need to inject the newsService and not the module name.
.controller('newsController', function($scope, newsService) {
newsService.getnews().then(
function(newsData) {
$scope.newsData = newsData
},
function optionalErrorhandler() {});
})
angular
.module('MyApp', [])
.controller('MyController', MyController)
.factory('MyService', MyService);
MyController.$inject = ['$scope','MyService'];
MyService.$inject = ['$http'];
function MyService($http){
var service = {
var myServiceFunction : function(){
$http({
// your http request on success return the data.
}).success(function(data)){
return data;
});
}
};
return service;
}
function MyController($scope, MyService){
MyService.myServiceFunction(); //Call service from the controller.
}

Getting Data From Service

Here is my controller and service:
var app = angular.module('myApp', ['ui.bootstrap']);
app.service("BrandService", ['$http', function($http){
this.reloadlist = function(){
var list;
$http.get('/admin.brands/getJSONDataOfSearch').
success(function(data, status, headers, config) {
list = data;
}).
error(function(data, status, headers, config) {
});
return list;
};
}]);
app.controller('BrandsCtrl', ['$scope','$http','$controller','BrandService', function($scope, $http, $controller, BrandService) {
$scope.brands = BrandService.reloadlist();
angular.extend(this, $controller("BrandCtrl", {$scope: $scope}));
}]);
I searched for this issue and tried answers of questions but I couldn't get solution. I am new at angular so can you explain with details; why I couldn't get the data from service to controller this way ?
The return used for data is for the callback of your function.
You must use the promise returned by $http like this.
In your service return the promise :
return $http.get('/admin.brands/getJSONDataOfSearch').
success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
});
Use then() on the promise in your controller :
BrandService.reloadlist()
.then(function (data){
$scope.brands = data;
});
It's not angular, it's the Javascript. The function you put in this.reloadlist does not return any value. It has no return at all, so the value returned will be undefined. The success handler does return something, but it will be run long after reloadlist finished working.
Besides what #fdreger already pointed out (missing return value), $http.get(...) is an async method. The return value is a promise not the actual value.
In order to access the value you need to return it from reloadlist like this:
this.reloadList = function() {
return $http.get('/admin.brands/getJSONDataOfSearch');
// you need to handle the promise in here. You could add a error handling here later by catching stuff...
}
and in the controller you can add it to the $scope like this:
BrandService
.reloadlist()
.then(function(res) {
$scope.brands = res.data;
});
The callback passed to then() is called as soon as the HTTP request has successfully completed, this makes the call asynchronous.
Besides the angular documentation for promises the article on MDN is a good read too.

AngularJS fail to inject a service

I have a simple service which grab data from HTTP end point send it back to controller.
I also implemnted caching in the service however, i get this error TypeError: undefined is not a function on this line of code in my controller
myappApi.getItems().then(function(data)
I tried to figure out why i couldn't.
here is the controller code:
.controller('ItemsCtrl',['$scope','myappApi',function($scope, myappApi){
myappApi.getItems().then(function(data){
$scope.items = data;
});
}])
As am using Ioniframework here how i injected my services in the app.js:
angular.module('myApp', ['ionic', 'myApp.controllers', 'myApp.services', 'angular-data.DSCacheFactory'])
and here is the code of my service:
(function() {
'use strict';
angular.module('myApp.services',[]).factory('myappApi', ['$http', '$q', '$ionicLoading', 'DSCacheFactory', myappApi]);
function myappApi($http, $q, $ionicLoading, DSCacheFactory) {
self.itemsCache = DSCacheFactory.get("itemsCache");
//to re-use expired cached data if no internet connection
self.itemsCache.setOptions({
onExpire: function (key, value) {
getItems()
.then(function () {
console.log("items items Cache was automatically refreshed.", new Date());
}, function () {
console.log("Error getting data. Putting expired item back in the cache.", new Date());
self.itemsCache.put(key, value);
});
}
});
function getItems() {
var deferred = $q.defer(),
cacheKey = "items",
itemsData = self.itemsCache.get(cacheKey);
if (itemsData) {
console.log("Found data inside cache", itemsData);
deferred.resolve(itemsData);
} else {
$http.get("services/data.json")
.success(function(data) {
console.log("Received data via HTTP");
self.itemsCache.put(cacheKey, data);
deferred.resolve(data);
})
.error(function() {
console.log("Error while making HTTP call.");
deferred.reject();
});
}
return deferred.promise;
}
return {
getItems: getItems
};
};
})();
Thank you for your time.
Take a look in the angular-cache file CHANGELOG.md :
"- Angular module renamed to angular-cache
- DSCacheFactory renamed to CacheFactory"
You will have to change:
app.js:
instead of 'angular-data.DSCacheFactory' use 'angular-cache'
service.js
instead of 'DSCacheFactory' use 'CacheFactory'
It looks like you've declared the myappApi factory before the myappApi function is actually defined. Try something like:
angular.module('myApp.services',[]).factory('myappApi', ['$http', '$q', '$ionicLoading', 'DSCacheFactory',
function($http, $q, $ionicLoading, DSCacheFactory) {
// myappApi code
}]);

Categories

Resources