I created a factory which is using the $resource factory, I want to customise the url params passed to the $resource according my current URL.
here's my code sample:
MyApp.factory("provider_services", ['$resource', function($resource) {
var factory = {};
var ProviderService = $resource("/providers/:provider/provider_services/", { format: 'json', provider: "pro" });
factory.services = ProviderService.query();
return factory;
}])
My current url is: somedomain.com/providers/pro/services/
I want to pull the "pro" part out of the url (that ideally can be anything else) and pass it in the provider param to the resource (in my current sample you can see it's hardcoded).
something like:
cur_provider = {get the current value from the url}
var ProviderService = $resource("/providers/:provider/provider_services/", { format: 'json', provider: cur_provider });
*I know I can do it using $location somehow, but I can't seem to access it within my provider_services factory.
Thanks !
You can use $routeParams to do this. It would look something like this:
angular.module('app').controller("ExampleController", ['$resource', '$routeParams', 'SomeService',
function($resource, $routeParams, SomeService) {
//The id here is whatever you name your route variable.
cur_provider = $routeParams.provider;
var ProviderService = $resource("/providers/:provider/provider_services/", { format: 'json', provider: cur_provider });
}
]);
Related
I am using ui-router for routing my angular app. I have set the routing configuration but didn't want to use controller as syntax. I am using following syntax:
.state('blog',{
url: '/blog',
templateUrl: '/templates/blog.html',
controller: 'BlogController'
})
However the template is being called into my ui-view but I BlogController is not being called. I have used console.log() into my BlogController but I didn't see anything in my console. Here is my BlogController.js
app.controller('BlogController', function($scope, PostService,){
console.log(0);
PostService.getPost().then(function(post){
$scope.postModel = post;
});
console.log(1);
});
As you can see, I am using a service to call data using $http. Below is my PostService :
app.service('PostService', function ($http) {
this.getPost = function () {
return $http({
method : 'GET',
url : 'http://domain.com/wp-json/wp/v2/posts'
})
.then(function(response){
return response.data;
}, function(error){
return error;
});
};
});
I think this the problem related to the service call. I have read some post about resolve property in state method of ui-router. I have tried that but nothing has working. Can somebody please help me to get rid out of this ?
The declaration of the ui-router module is wrong
var app = angular.module('mySiteApp', [require('angular-ui-router')])
Should be,
var app = angular.module('mySiteApp', ['ui.router'])
Check this link for cors errors
Following is my $routeProvider.when
.when("/products/:id",{
templateUrl:"app/views/product.html",
controller:"productController"
})
I want to access the value of :id in the product controller.
Based on which i will populate product details.
the url is /index.html#/products/3
You can use $routeParams.id in your controller.
You can access it in your controller with $routeParams
app.controller('productController', function ($scope, $routeParams) {
$scope.productId = $routeParams.id;
};
Read more here
$stateParams are for custom ui-router
Inject $routeParams to your controller factory function.
.controller('MainController', function($scope, $routeParams) {
$scope.id= $routeParams.id;
})
Use the $location service
To access any part of a path you need to use the $location service. It lets you use different parts of the url. For instance (From docs)
// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var url = $location.url();
// => "/some/path?foo=bar&baz=xoxo"
But what you want is this
// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var path = $location.path();
// => "/some/path"
This will return a string that is everything after the #
so then you can Use slice or some other JS function to get the part you need.
Best of luck
I am working on an angular project and I am using $ resource for the first time. I currently have just as a test to get data out of my database a service that has one call to $resource
Here is my service:
(function() {
"use strict";
angular.module("commonServices")
.factory("ptaResource",
["$resource", ptaResource]);
function ptaResource($resource) {
return $resource("http://localhost:55928/api/excercises", {}, { 'query': { method: 'GET', isArray: true } });
}
})();
My question is this. I have a lot of calls to make to various controllers and methods within those controllers. I cant wrap my head around how to structure a service that allows me to call it with an endpoint listed
I tried doing something like this:
var services =[
getExercises: getExercises,
doSomething: doSomething
];
return service;
function getExercises (){
return $resource request here
}
But that did not work, I have looked on line but any tutorial is only exposing one of each type of request. I am going to have several get requests to controllers, some with different query strings. I will be querying different controllers as well. The purist in me tells me that all of this belongs in one place.
What would be a good method for doing this one large service with a way to call each request individually. Should I break them into a service per web api controller. Any input would be appreciated.
Thanks,
John
If you wanted to wrap your resources in a service, you could do something like this:
angular
.module('commonServices', ['ngResource'])
.factory('ptaResource', ['$resource', function($resource) {
return $resource('http://localhost:55928/api/excercises/:excerciseId', {
excerciseId: '#id'
});
}])
.service('CommonService', ['ptaResource', function(ptaResource) {
return {
getExercises: function() {
return ptaResource.query().$promise;
}
};
}]);
Then you could call it like so:
angular
.module('app', ['commonServices'])
.controller('SomeController', ['$scope', 'CommonService', function($scope, CommonService) {
$scope.exercises = CommonService.getExercises();
// or
CommonService.getExercises().then(function(exercises) {
$scope.exercises = exercises;
}).catch(function(err) {
// handle error here
});
}]);
When user arrive to following URL
mainurl/exampleurl?token=23
i can extract the "exampleurl" using this $state.$current.name
How can i exctract the token=23 from this url
You can get parameters from $stateParams:
https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service
var token = $stateParams.token
Hope it helps
Option-1: You can use $location service.
var t = $location.search().token
Option-2 If you are using ui-router, you may access the querystring parameters from $stateParams service too
var t = $stateParams.token
Cheers!
Try passing $location to your controller and use it like this.
.controller('YourController', ['$scope', '$stateParams', '$location' , function ($scope, $stateParams, $location) {
// Get token from query string
var token = $location.search().token;
}
You can get parameters with $location.search() into your controller. See below
// Given URL
// mainurl/exampleurl?token=23
var searchObject = $location.search();
// => {token: 23}
This might be a beginner question, but I am retrieving data via http calls in AngularJS and setting them as properties in the $scope variable. However, since http calls take a while, my page tries to load AngularJS more than once in order to render different parts of the page as more the data is retrieved. Is there a way around this? (to hold off on loading the page before all data has been retrieved)
What you could do is to use ng-hide or ng-cloak, so that whatever should not be displayed until the http call fully loaded the data would remain hidden.
take a look at the resolve property in the route settings. If you set something to be resolved the router will resolve this before going to the controller.
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "app.html",
controller: "AppCtrl"
resolve: {
app: function ($q, $timeout) {
YourFactory.getData({});
}
}
}
)
});
then create a Factory that will get the data you need
app.factory('YourFactory', ['$http', '$q',
function($http, $q) {
var url = '/api2.php/api';
var YourFactory = {};
var factory_data = [];
var messages = [];
YourFactory.getData = function(params) {
console.log("into GET data");
var deferred = $q.defer();
$http.get(url).success(function(response) {
angular.copy(factory_data, response.data);
deferred.resolve();
}).error(function(response) {
//couldn't resolve therefore it's rejected
deferred.reject();
});
//returns a promise that indicates that something is being resolved and will be returned for the app to continue
return deferred.promise;
};
YourFactory.data = function() {
return factory_data;
};
return YourFactory;
}
]);
then in your controller you need to input the factory and set the scope data from the Factory. Remember that Angular used the Factory to get data before the controller using the resolve property.
app.controller("AppCtrl", ['$scope','YourFactory',
function($scope, YourFactory) {
$scope.data = YourFactory.data();
});
(I haven't tested the code, I simply wrote an example based on an app that I'am doing and in which I passed through the same things as you)
Look at this links if you have any doubt.
https://egghead.io/lessons/angularjs-resolve
http://www.javierlerones.com/2013/07/preloading-data-using-deferred-promises-in-angular-js.html