I'm using external mongodb and wrote a node/express server for fetching the data on my localhost.
I query localhost like this:
http://localhost:8888/api/bonsais
And I'm getting the correct results from my mongodb collection # mongolab.
[{"name":"test,test2","_id":"536be2e2ae54668818000001","__v":0},{"name":"testname","_id":"536fd2df41f84a581c000001","__v":0}]
I wrote a service to fetch the data like this:
angular.module('bonsaiService', ['ngResource']).
factory('bonsaiService', function($resource) {
return $resource('http://localhost:8888/api/bonsais',{'query': {method: 'GET', isArray: true }});
});
I'm getting a Error: [$resource:badcfg] object, which is referring to these error docs
.factory('Bonsai', function($q, $resource){
var bonsaiResource = $resource('http://localhost:8888/api/bonsais', {}, {
get: {
method: 'GET',
isArray: true
}
});
return {
get: function() {
var q = $q.defer();
bonsaiResource.get({
},
function(resp) {
q.resolve(resp);
}, function(httpResponse) {
q.reject(httpResponse);
});
return q.promise;
} };
})
try to write it this way.
Then you can call it with Bonsai.get()
Thanks #thesearentthedroids, your responds fixed it for me!
Just to follow up, I've used the following to retrieve the data in my controller:
bonsaiService.get($scope.trees).then(
function(data){
$scope.trees = data;
});
Related
I ve got an angular resource service which then returns the data to a controller and I get all the data plus the data by name.
My application works just fine in the browser but I get a resource error in the console. Bad resource configuration.
I had a look in various questions and everyone states that I need to set the configuration property isArray to either false or true.
I have tried to do this but I still get an error.
Any ideas much appreciated.
Here is my service :
(function() {
var app = angular.module('test');
app.service('ContactResource', function($resource) {
return $resource('/contacts/:firstname', {},
{'update': {method: 'PUT'}},
{'query': { method: 'GET', isArray: true }},
{'get': { method: 'GET', isArray: false }}
);
});
}());
And here is my controller:
(function() {
var app = angular.module('test');
app.controller('contactsCtrl', function($scope, $routeParams, ContactResource) {
$scope.contacts = ContactResource.query();
$scope.singlecontact = ContactResource.get({firstname: $routeParams.firstname});
});
}());
The error I am getting is : Error: [$resource:badcfg] http://errors.angularjs.org/1.4.2/$resource/badcfg?p0=get&p1=object&p2=array&p3=GET&p4=%2Fcontacts
When I click it says :
Error in resource configuration for action get. Expected response to contain an object but got an array (Request: GET /contacts)
When I get the url is /contacts the response is :
[{EmailAddress:some#email.com, etc}]
When the url is /contacts/firstname the response is :
{EmailAddress:some#email.com,etc}
I solved the problem by adding a new controller called single controller and by separating the service into two functions. Here is how my code looks like now.
This is the service:
(function() {
var app = angular.module('test');
app.service('ContactResource', function($resource, $routeParams) {
this.all = function() {
return $resource('/contacts', {},
{'query': { method: 'GET', isArray: true }}
)};
this.single = function() {
return $resource('/contacts/:firstname', {firstname: '#firstname'},
{'query': { method: 'GET', isArray: false }}
);
}
});
}());
And the controllers :
(function() {
var app = angular.module('test');
app.controller('contactsCtrl', function($scope, $routeParams, ContactResource) {
$scope.contacts = ContactResource.all().query();
});
app.controller('singleCtrl', function($scope, $routeParams, ContactResource) {
$scope.singlecontact = ContactResource.single().query({firstname: $routeParams.firstname});
});
}());
For some reason which I am still not sure $resource wouldn't accept them into the same controller.
I try to get response data from angular service created by factory and $resource. I want to send POST request to server to create object in db and received created ID.
So I create service like this:
angular.module('sample')
.factory('Client', function ($resource) {
return $resource('api/clients/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
I use Client service in controller:
$scope.create = function () {
Client.save($scope.client,
function (response) {
$state.go("clientDetail", {'id' : whereIsMyId.id? })
});
};
Unfortunately, I do not know how to read data in response.
As response I just get number like "6" but this could be any JSON.
Thank you.
I'm trying to create a Service in Angularjs to make use of various oEmbed providers including YouTube.
...
myServices.factory('YouTubeService', function ($resource) {
//how can I make the URL part dynamic?
return $resource('http://www.youtube.com/oembed/', {}, {
query: { method: 'GET', isArray: true },
})
});
...
The oEmbed URL structure is http://www.youtube.com/oembed?url=<url_of_video>
How can I make this service work with any YouTube URL provided by the user? In other words, can I call this Service from my Controller and pass in the URL in some way?
YouTubeService.query(<url here maybe>)
Here you go, this should work, I think.
myServices.factory('YouTubeService', function ($resource) {
var youtubeservice = {};
youtubeservice.query = function(urlProvided){
return $resource('http://www.youtube.com/oembed?url=:urlProvided', {}, {
query: { method: 'GET', isArray: true },
});
}
return youtubeservice;
});
Invoke:
YouTubeService.query(<url here>)
I am not sure if you can access external url like this(may throw cross domain error)
But for your question, why don't you use a service instead of factory like this
myServices.service('YouTubeService', function ($resource) {
//how can I make the URL part dynamic?
this.getStuff = function(url){
return $resource(url, {}, {
query: { method: 'GET', isArray: true },
}).query();
}
});
And invoke it like
YouTubeService.getStuff (dynamicUrl);
how to make Generic method for rest call in angularjs ?
i have tried for single request, it's working fine
UIAppRoute.controller('test', ['$scope', 'checkStatus', function($scope, checkStatus) {
$scope.data = {};
checkStatus.query(function(response) {
$scope.data.resp = response;
});
}])
UIAppResource.factory('checkStatus', function($resource){
return $resource(baseURL + 'status', {}, {'query': {method: 'GET', isArray: false}})
})
I want to make this as generic for all the request
Please share any sample,.. thanks in advance
I'm using something like this :
.factory('factoryResource', ['$resource', 'CONF',
function($resource, CONF) {
return {
get: function(endPoint, method) {
var resource = $resource(CONF.baseUrl + endPoint, {}, {
get: {
method: method || 'GET'
}
});
return resource.get().$promise;
}
};
}
])
called by :
factoryResource.get(CONF.testEndPoint, "POST"); // make a POST and return a promise and a data object
factoryResource.get(CONF.testEndPoint, "GET"); // make a GETand return a promise and a data object
factoryResource.get(CONF.testEndPoint); // make a GETand return a promise and a data object
with a config file having :
angular.module('app.constant', [])
.constant('CONF', {
baseUrl: 'http://localhost:8787',
testEndPoint: '/api/test'
});
I have an Angular service/provider that serves json data to my controller which works great:
angular.module('myApp.services', ['ngResource']).
factory("statesProvider", function($resource){
return $resource('../data/states.json', {}, {
query: {method: 'GET', params: {}, isArray: false}
});
});
But I also need to serve json data to the same controller from another file counties.json.
Where can I find out how to I write a service that serves both files to my controller?
You can update service to return a hash of resources, not a single one:
angular.module('myApp.services', ['ngResource']).
factory("geoProvider", function($resource) {
return {
states: $resource('../data/states.json', {}, {
query: { method: 'GET', params: {}, isArray: false }
}),
countries: $resource('../data/countries.json', {}, {
query: { method: 'GET', params: {}, isArray: false }
})
};
});
You will be able to use it adding .query() at the end your function name i.e. geoProvider.states.query() and geoProvider.countries.query() and myApp.services has to be injected into your controller, then inject geoProvider service into controller itself as well.
I'm assuming you want to execute some code when both files have loaded. Promises work really well for this. I don't think resources return promises, but you can use the $http service for simple ajax calls.
Here I define one service each for the two data files, and a third service that returns a promise that gets fulfilled when both files are done loading.
factory('states',function($http) {
return $http.get('../data/states.json');
}).
factory('countries',function($http) {
return $http.get('../data/countries.json');
}).
factory('statesAndCountries', function($q, states, countries) {
return $q.all([states, countries]);
});
Then in your controller:
statesAndCountries.then(function(data) {
var stateData = data[0];
var countryData = data[1];
// do stuff with stateData and countryData here
});