i'm new to angularjs and trying to access a service method which uses $resource to make a call to my rest api. But when i'm trying to access its giving a error. also when i try to access a method which does not use $resource it works fine.
here's my code.
app.factory('userService', ['$resource',
function($resource) {
var factory = {};
factory.authenticatedUser;
factory.test = function(){
return "Test";
};
factory.getLoggedInUser = function(){
$resource('api/user', {}, {
query: {method: 'GET'}
});
};
factory.getAuthenticatedUser = function(){
return factory.authenticatedUser;
};
factory.setAuthenticatedUser = function(user){
factory.authenticatedUser = user;
};
return factory;
}]);
here's how i'm trying to access the method.
userService.getLoggedInUser.query(function(loggedInUser) {
});
this throws the following error.
TypeError: userService.getLoggedInUser.query is not a function
but this works fine.
var text = userService.test();
What am i doing wrong here?
You need to add a $ sign. And return the $resource object from your function
factory.getLoggedInUser = function(){
return $resource('api/user', {}, {
query: {method: 'GET'}
});
};
userService.getLoggedInUser().$query(function(loggedInUser) {
});
Related
I am currently trying to store a $http JSON request to a variable in a factory and then retrieve the value of that variable in a controller.
Currently all I receive back is undefined. I imagine the AJAX request isn't finished running before the function gets called. I am new to Angular so trying to grab any basic concepts I can and helpful knowledge.
app.factory('typiCode', function($http) {
var jsonService = {
async: function() {
var promise = $http.get('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
console.log(response);
return response.data;
})
return promise;
}
};
return jsonService;
});
app.controller("getJson", function($scope, typiCode) {
$scope.returnedData = typiCode.jsonService;
$scope.logResults = function() {
var theData = $scope.returnedData;
console.log(theData);
}
});
<button ng-click="logResults()">Launch data</button>
Thank you in advance!
Your typiCode factory returns your jsonService object. So you should be calling typiCode.async() somewhere in your code.
You could do, for example, like this in your controller:
app.controller("getJson", function($scope, typiCode) {
typiCode.async()
.then(function(data) {
$scope.returnedData = data;
})
$scope.logResults = function() {
var theData = $scope.returnedData;
console.log(theData);
}
});
My approach is using AngularJS Service instead of factory along the project. Now I want to build an object called MyData which should be used as array in angularJS controller, such as:
vm.datas= MyData.query({}, function (datas) {
vm.thisData = {selected: datas[0].id};
});
As I searched in questions, I understood I can use factory as below:
angular.module('myDataService', ['ngResource']).
factory('MyData', function($resource){
return $resource(myURL, {}, {
query: {method:'GET', isArray:true}
});
});
What should I do if I want to use service. Is the code correct, below? What is the best practice?
angular
.module('app')
.service('myDataService', myDataService);
myDataService.$inject = ['ngResource'];
function myDataService($resource) {
var self = this;
self.MyData = $resource(myURL, {}, {
query: { method: 'GET', isArray: true }
});
}
I'm trying to use JSONP with Restangular. I'm using the Songkick API and when making a GET request I'm receiving no response data from a different domain but locally I receive data no problem.
I've created the following Factory for configuring Restangular and a controller. I'm a little unsure about how to use setDefaultRequestParams. Maybe the configuration is incorrect?
angular
.module('ModuleName')
.factory('RestFactory', Factory);
function Factory (Restangular) {
var factory = {
songkick: songkick
};
return factory;
function songkick () {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setJsonp = true;
RestangularConfigurer.setDefaultRequestParams('jsonp', {
callback: 'JSON_CALLBACK'
});
RestangularConfigurer.setDefaultRequestParams('get', {
reason: 'attendance',
apikey: 'xxxxxxxxxx'
});
RestangularConfigurer.setBaseUrl('http://api.songkick.com/api/3.0/');
RestangularConfigurer.setRequestSuffix('.json');
RestangularConfigurer.setDefaultHttpFields({cache: true});
});
}
}
angular
.module('ModuleName')
.controller('UserController', Controller);
function Controller ($stateParams, RestFactory) {
var user = this;
activate();
function activate () {
RestFactory.songkick().one('users/'+$stateParams.username+'/calendar')
.get()
.catch(function(response){
console.log("Error with status code", response.status);
});
}
}
Did you miss the JSONP option settings for Restangular?
Something like the following:
//JSonp
RestangularProvider.setJsonp(true);
RestangularProvider.setDefaultRequestParams('jsonp', {callback: 'JSON_CALLBACK'});
Documented here
I'm totally new to AngularJs and I have this problem I do not understand. I have two methods. The first one takes some data from a webservice and puts in in a variable defined in the scope. But when I want to use that variable in the second method it is undefined. Can someone help me understand why this is happening and provide a solution?
var myApp= angular.module( "myApp", [] );
myApp.controller("myAppController",
function( $scope ) {
$scope.getAll = function(){
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
url: ..something...,
success: function (parameters) {
$scope.profiles = angular.copy(parameters); <-- correct data is returned
$scope.$apply();
},
error: function () {
alert("Error calling the web service.");
}
});
}
$scope.getCategories = function(){
var all = $scope.profiles; <-- At this point profiles is empty
...
}
$scope.getAll();
$scope.getCategories();
}
Use the $http service and promises:
$scope.profiles = $http.jsonp(url).then(function(r){ return r.data; });
$scope.categories = $scope.profiles.then(function(profiles) {
var params = { }; // build url params
return $http.jsonp(url, { params: params }).then(function(r){ return r.data; });
});
When you call getCategories(), getAll() hasn't finished yet, which is why profiles is empty. There are several ways to solve this. The best way would be to use promises the built-in $http service.
If you prefer to use jQuery, you can add a watcher on the profiles variable and only when it's populated run the getCategories().
Something like this should work:
$scope.getAll = function(){
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
url: ..something...,
success: function (parameters) {
$scope.profiles = angular.copy(parameters); <-- correct data is returned
$scope.$apply();
},
error: function () {
alert("Error calling the web service.");
}
});
}
$scope.getCategories = function(){
var all = $scope.profiles;
}
// Wait for the profiles to be loaded
$scope.watch('profiles', function() {
$scope.getCategories();
}
$scope.getAll();
There is no guarantee that getAll has completed before getCategories is invoked, since it is an asynchronous request. So if you want to sequentially invoke getAll and getCategories, you should invoke getCategories inside the success callback of getAll. You could also look into promises for a neater way of chaining asynchronous callbacks (I assume you're using jQuery since you're calling $.ajax).
...
<snipped some code>
success: function(parameters) {
// snipped more code
$scope.getCategories();
}
(and if you're using jQuery promises)
$.ajax(ajaxCallOneOpts).then($.ajax(ajaxCallTwoOpts));
Neither are very "Angularish" though, so you might want to look into some of the provided services for working with http/rest resources instead of using jQuery.
Why are you using a jQuery ajax request in angular? If you write jQuery style code and wrap it angular, you're going to have a bad time...
Here is an angularised version:
myApp.controller("myAppController",
function( $scope, $q, $http ) {
$scope.getAll = function(){
var deferred = $q.defer();
$scope.profiles = deferred.promise;
$http.jsonp('your url').then(function(data) {
deferred.resolve(data);
});
});
$scope.getCategories = function(){
$q.when($scope.profiles).then(function(profiles) {
... <-- At this point profiles is populated
});
}
$scope.getAll();
$scope.getCategories();
}
I'm working with Angular factory and trying to make a webservice call, but looks like it is not recognizing $resource.
.factory('User', function($resource) {
function login() {
// THIS IS NOT WORKING, how do I make a webservice call from here?
$resource('/api/user.json', {}, {
method: 'POST',
isArray: false
});
return true;
}
function logout() {
return false;
}
return {
login : function() { return login(); },
logout: function() { return logout(); }
};
Thanks,
Tee
i assume you have the resource module file somewhere :
https://raw.github.com/angular/angular.js/master/src/ngResource/resource.js
you need to import the proper module in your app :
var App = angular.module("App",["ngResource"]);
then use it in a "sane" way :
var User = App.factory("User",function($resource){
var User = $resource('/api/user.json',{},{
login:{method:"POST",isArray:true},
logout:{method:"POST"}
});
return User;
// use User in your controller or another service.
});
the doc is here : http://docs.angularjs.org/api/ngResource.$resource