I have an angularjs factory to get data via $http.get():
'use strict';
app.factory('apiService', ['$http', function ($http) {
var apiService = {};
apiService.urlBase = 'http://localhost:1337/api/';
apiService.get = function (urlExtension) {
$http({
method: 'GET',
url: apiService.urlBase + urlExtension
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
});
}
return apiService;
}]);
The problem is, that it always returns undefined when i call the method apiService.get(); in a Controller. When I log the response data in the factory, it display the right data. The apiService.urlBase variable is always filled in my controller.
Do you guys have any suggestions or am I doing something wrong? Maybe it's a syntax error.
You are not returning the promise that is returned by $http. Add return before $http
Okay I solved the problem. I just passed a callback function via parameter for my get() function.
'use strict';
app.factory('apiService', ['$http', function ($http) {
var apiService = {};
apiService.urlBase = 'http://localhost:1337/api/';
apiService.get = function (urlExtension, callback) {
var data = {};
$http({
method: 'GET',
url: apiService.urlBase + urlExtension
}).then(function successCallback(response) {
data = response.data;
callback(data);
}, function errorCallback(response) {
console.log(response);
});
return data;
}
return apiService;
}]);
Related
I have a config.prop file which is being called from ngConfig.js file which is a service file. This prop file contains an URL which I need in my 2nd service file ngContent.js .
These files are being called individually from resolve.
$routeProvider.
when('/login', {
templateUrl: 'views/login.html',
controller: LoginController,
resolve: {
urlData: function(Config) {
return Config.prop().then(function(response) {
return response;
});
},
contentData:function(Content){
return Content.prop().then(function(response){
return response;
});
}
}
})
The response I am getting from urlData, which is resolving my response from ngConfig.js is the content of the config.prop. I need this response in my ngContent.js file.
The content of ngConfig.js is
angular.module('ngConfig', [])
.service('Config', function ($http, $rootScope, $document) {
//API calling method for all method
this.prop = function () {
try {
//API calling
var promise = $http({
method: 'GET',
dataType: "application/json",
data: 'json',
cache: false,
url: 'config.prop',
}).then(function (response) {
return response;
}, function (response) {
return response;
});
} catch (ex) {
return ex;
}
return promise;
};
});
The content of ngContent.js is
angular.module('ngContent', [])
.service('Content', function ($http, $rootScope, $document) {
//API calling method for all method
this.prop = function () {
try {
//API calling
var promise = $http({
method: 'GET',
dataType: "application/json",
data: 'json',
cache: false,
url: API_URL
}).then(function (response) {
return response;
}, function (response) {
return response;
});
} catch (ex) {
return ex;
}
return promise;
};
});
The API_URL is present in config.prop file, which is called from ngConfig.js file.
I hope I was able to present my problem clearly.
Thanks in advance.
You may pass urlData to contentData, like this, and then pass it to Content.prop().
contentData: function(Content, urlData){
return Content.prop(urlData).then(function(response){
return response;
});
}
Edit
This doesn't work with $routeProvider, you have to use $stateProvider of ui-router.
I have used it and it works. Use it the same way as discussed above.
I'm sending http post request to REST api, I'm getting status ok response from server but in this script, it always runs 'myError' function. In backend everything is running fine without any error. In error function also response value remains undefined.
var toDoApp = angular.module('toDoApp');
toDoApp.factory('registrationService', function() {
var register = {};
register.registeruser = function(user, $http) {
$http({
method : "POST",
url : 'register',
data : user
}).then(function mySuccess(response) {
console.log("success");
}, function myError(response) {
console.log("error");
});
}
return register;
});
Inject the http service to the factory. Not the registeruser function.
toDoApp.factory('registrationService', function($http) {
Do some needful correction.
var toDoApp = angular.module('toDoApp',[]);
toDoApp.factory('registrationService', function($http) {
var register = {};
register.registeruser = function(user) {
$http({
method : "POST",
url : 'register',
data : user
}).then(function mySuccess(response) {
console.log("success");
}, function myError(response) {
console.log("error");
});
}
return register;
});
Error is showing because you did not inject $http service to to your toDoAppfactory not in your registeruser function . You should inject $http service to your factory. like :
toDoApp.factory('registrationService', function($http)
And your function registeruser should be like
register.registeruser = function(user) {
$http({
method : "POST",
url : 'register',
data : user
}).then(function mySuccess(response) {
console.log("success");
}, function myError(response) {
console.log("error");
});
}
I am trying to use angular's http cache but the result is undefined. Cache returns an object but usersCache is undefined.
controller in main.js
app.controller('exploreController', function($scope, dataService, $cookies, $cacheFactory, $http) {
// dataService.explorePosts();
$scope.explore = function(){
dataService.explorePosts();
var cache = $cacheFactory.get('$http');
console.log(cache);
var usersCache = cache.get('http://dstm.herokuapp.com/api/explore');
console.log(usersCache);
};
$scope.explore();
});
service in data.js
angular.module('dsnApp')
.service('dataService', function($http, $cookies, $cacheFactory) {
this.explorePosts = function(){
var id = $cookies.get("userId");
$http.get('http://dstm.herokuapp.com/api/explore', {cache: true,
params: {userId: id, page: 1},
})
.then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
#charlietfl is right.
$http is asynchronous.Nothing will be cached until the request
completes and you are trying to access the cache synchronously.
To make this work as you expect:
First, make the this.explorePosts function return the promise, which $http service alredy returns.
this.explorePosts = function(){
var id = $cookies.get("userId");
return $http.get('http://dstm.herokuapp.com/api/explore', {cache: true,
params: {userId: id, page: 1},
})
.then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
Then use the cache in the promise's then callback.
$scope.explore = function() {
dataService.explorePosts().then(function () {
var cache = $cacheFactory.get('$http');
console.log(cache);
var usersCache = cache.get('http://dstm.herokuapp.com/api/explore');
console.log(usersCache);
});
};
Why is it that when I try to retrieve data with this simple API call I get an error that says http://127.0.0.1:8080/%7B%7Buser.avatar%7D%7D <- ? But if I move my promise into my controller it works. I thought that you can make your promises in your service and it'll work fine?
This is my controller.js file
angular.module('userProfiles').controller('MainController', function($scope, mainService) {
$scope.getUsers = function() {
mainService.getUsers();
}
$scope.getUsers();
});
This is my services.js file
angular.module('userProfiles').service('mainService', function($http) {
var baseUrl = 'http://reqres.in/api/users?page=1';
this.getUsers = function() {
return $http({
method: 'GET',
url: baseUrl
}).then(function(response) {
this.users = response.data.data;
});
}
});
You aren't assigning the response.data.data to anything usable outside that callback. Try it like this instead, returning a promise that resolves with the users data...
this.getUsers = function() {
return $http.get('http://reqres.in/api/users', {
params: {page: 1}
}).then(function(res) {
return res.data.data;
});
};
and in your controller
$scope.getUsers = function() {
mainService.getUsers().then(function(users) {
$scope.users = users;
});
};
I'm trying to build an angular service I can reuse for doing my http requests etc. This all works when it's not in a service.
The following code works and does the login, but the log of $scope.data is always undefined. If i put a log in on the success before I return data it returns the data, but not back to the controller which is what i'm really looking to do.
Just for clarification, I want to be able to access the json data returned from the server as 'data' in the success in my controller.
//App.js
.service('SaveSubmitService', function ($http, $log) {
this.addItem = function(url, options){
var xsrf = $.param({
Username: options.Username,
Password: options.Password
});
$http({
method: 'POST',
url: url,
data: xsrf,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
console.log(data);
return false;
});
}
})
Controller:
.controller('LoginCtrl', function ($scope, $stateParams, $location, $ionicLoading, $http, SaveSubmitService, $log) {
if (localStorage.getItem("SessionKey")) {
$location.path('home');
}
$scope.login = {};
$scope.doLogin = function doLogin() {
$scope.data = SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login);
$log.info($scope.data);
};
})
First of all make SaveSubmitService return promise object. Then use its API to provide a callback to be executed once data is loaded:
.service('SaveSubmitService', function ($http, $log) {
this.addItem = function (url, options) {
var xsrf = $.param({
Username: options.Username,
Password: options.Password
});
return $http({
method: 'POST',
url: url,
data: xsrf,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
return response.data;
})
.catch(function(error) {
$log.error('ERROR:', error);
throw error;
});
}
});
And the you will use it like this in controller:
$scope.doLogin = function doLogin() {
SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login).then(function(data) {
$scope.data = data;
$log.info($scope.data);
});
};
Note, how you return result of $http function call, it returns Promise which you use in controller.
saveSubmitService Service method is returning promise and it can be resolved using .then(function())
Your controller code will look like below.
CODE
$scope.doLogin = function doLogin() {
var promise = saveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login);
promise.then(function(data) {
$scope.data = data
});
};
Thanks
.factory('SaveSubmitService', function ($http, $log) {
return{
getData:function(url,xsrf)
{
$http({
method: 'POST',
url: url,
data: xsrf,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
console.log(data);
return false;
});
}
}
})
.controller('LoginCtrl', function ($scope, $stateParams, $location, $ionicLoading, $http, SaveSubmitService, $log) {
if (localStorage.getItem("SessionKey")) {
$location.path('home');
}
$scope.login = {};
$scope.doLogin = function doLogin() {
$scope.data = SaveSubmitService.addItem(, );
$log.info($scope.data);
};
SaveSubmitService.getData('http://*****/Services/Account.asmx/Login',$scope.login).success(function(data,status){
$scope.data
}).error(function(data,status){ });
)};