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 }
});
}
Related
I need to set a factory variable in my controller. This variable is used for the url for returning a save function in my factory. I actually build this url as several pieces but this is a simplified version.
myApp.factory('SaveDate', ['$resource',
function saveDateFactory($resource, $http) {
var myData = '';
return $resource(myData, {}, {
query: { method: "POST", params: {}, isArray: false },
});
}]);
The function from my controller looks like this:
vm.myFunction1 = function ($resource) {
vm.myDate = '/test/MyProduct/SetSalesDate/988093099/108/2016/05/21';
SaveDate.myData = vm.myDate;
//this should save the date for milestones
SaveDate.query();
vm.cleanUp();
};
I have tried using an object instead of a primitive but it also didn't work. I have tested and my value for SaveDate.myData is being set accurately. If I hard code a value in the spot where I declare my variable in the factory, it will save perfectly. I am just not able to pass the variable successfully from my controller to my factory. I have tried a wide variety of ways to do this including using $watch. Thanks for your help on this!
When I added a function like this:
myApp.factory('SaveDate', ['$resource',
function saveDateFactory($resource, $http) {
var myData = {};
myData.getMyUrl = function (urlStuff) {
alert("in SaveDate" + urlStuff);
return $http.get(urlStuff);
}
return $resource(myData.getMyUrl, {}, {
query: { method: "POST", params: {}, isArray: false }
Adding this function throws the following error: Unknown provider: myDataProvider <- myData <- UserListController
You'll need to create a function in your factory as Clint said in the comments.
myApp.factory('SaveDate', ['$resource',
function saveDateFactory($resource, $http) {
var myData = '';
function setMyData(data) {
myData = data;
}
return {
setMyData: setMyData,
resource: $resource(myData, {}, {
query: { method: "POST", params: {}, isArray: false },
})
};
}]);
In your controller:
SaveDate.setMyData(vm.myDate);
Getting the list is not a problem but if I tried to Update or Add a record, it does not seem to work.
Here's the code:
angular.module('userApp.services',[])
.factory('User', function($resource){
return $resource('http://localhost/api/v1/users/:id',
{id:'#id'},
{
update: {
method: 'PUT'
}
});
});
My RESTful service is built in Laravel.
You are not injecting the ngResource module you need to use.
angular.module('userApp.services',['ngResource'])
.factory('User', ['$resource', function($resource){
return $resource('http://localhost/api/v1/users/:id', { id:'#id' }, {
update: { method: 'PUT' }
});
}]);
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) {
});
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);
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
});