Angularjs appended $resource paramDefaults with special charaters - angularjs

I have the following code
var resource = $resource('https://api.mongolab.com/api/1/databases/' + DB_NAME + '/collections/' + collectionName + '/:id',
{ apiKey:API_KEY, id:'#_id.$oid'},{update:{ method:'PUT' } }
);
when i call
$scope.projects = Project.query({q:"+"});
referencing
Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.
I append the Get request with the string in the {}. I cannot however include special charaters. Is this a feature and how can I implement special characters?

I believe you should urlencode values as long as you are sending them in url query

Related

Passing array value to a query string url

I have an array of id let's say
favorites = [102,110,112,125]
I want to retrieve the corresponding object for each id by passing it to query string like this :
public getFavorites(favs){
let favorites = favs.join();
let encodedUrl = encodeURIComponent(JSON.stringify({"id": favorites }));
return this.http.get(this.api_url + '/1/query/data/getFavs?parameters='+encodedUrl, {
headers: this.authHeader
})
.retry(3)
.map(res => res.json());
}
The problem is only one object appear in my html template and also in the console. What is the best way for me to pass an array of value to a URL as parameters in order to retrieve the associated objects?
You can pass multiple parameter values with the same name over the querystring. Does that help you? For example, here's a snippet:
this.api_url + '/1/query/data/getFavs?id=101&id=110
Here is another answer that has some more info on this.
If you have to send the ID's over in a serialized manner, consider posting the JSON instead of using the GET method. If you're trying to maintain adherence to REST verb standards by making it a get call, can you post the server code?

AngularJS Directive to modify URL

In my templates i am able to display an image from my data using
ng-style="{'background-image':'url({{f.flower.imageURL}})'}"
The imageURL always returns a hi-res image with URL such as
https://s3.amazonaws.com/images/FlowerImages/Rose_1920.jpg
However the endpoint also has smaller images such as
https://s3.amazonaws.com/images/FlowerImages/Rose_320.jpg
https://s3.amazonaws.com/images/FlowerImages/Rose_480.jpg
https://s3.amazonaws.com/images/FlowerImages/Rose_1024.jpg
How would i create a directive to traverse back through the URL up to the underscore and pass in a size i want (depending on the view) to update between the underscore and the .jpg?
Based on you example, I don't think you need a directive. Just add a function to your controller.
Instead of
ng-style="{'background-image':'url({{f.flower.imageURL}})'}"
do
ng-style="{'background-image':'url({{generateImageUrl(f.flower.imageURL, 320)}})'}"
And your controller would have standard javascript to manipulate the url:
function generateImageUrl(url, size) {
var n = url.lastIndexOf("_");
var beforeUnderscore = url.substring(0, n);
var afterUnderscore = url.substring(n+1);
var suffix = afterUnderscore.split('.')[1];
return beforeUnderscore + "_" + size + "." + suffix;
}
The same function could work for image as well
<img ng-src="{{generateImageUrl(f.flower.imageURL, 320)}}">
Note: ng-src is used instead of src to prevent the browser from requested the url before angular has bootstrapped.

ng $resource Fails to Dynamically Generate URI

The Problem:
I have code to set up a $resource that seems to compile without error:
var ReportsRest = $resource('/reports/:reportId', {reportId: '#id'});
ReportsRest.get({id: 123});
but when that code actually executes the request url that is generated looks like this:
GET http://localhost:5523/reports?id=123 404 (Not Found)
The id is not being parsed and dynamically loaded into the URI. Is there something that I am missing?
Plunkr
http://plnkr.co/edit/3ikqMsnDI9r9LThaQLf3?p=preview
Try this:
var ReportsRest = $resource('/reports/:reportId', {reportId: '#id'});
ReportsRest.get({reportId: 123});
Under $resource Usage, there is this block of text.
paramDefaults
Default values for url parameters. These can be overridden in actions methods. If any of the parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).
Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.
Given a template /path/:verb and parameter {verb:'greet', salutation:'Hello'} results in URL /path/greet?salutation=Hello.
If the parameter value is prefixed with # then the value for that parameter will be extracted from the corresponding property on the data object (provided when calling an action method). For example, if the defaultParam object is {someParam: '#someProp'} then the value of someParam will be data.someProp.
To summarize, the object you pass in needs to use the key of your paramDefaults object to get the value. That value replaces the same :key text in your URL pattern. Any value in the paramDefaults object that is prefixed with an # will be set on the returned model data as a property named whatever follows the #.
var ReportsRest = $resource('/reports/:reportId', {reportId: '#id'});
ReportsRest.get({
reportId: 123,
other: 123
}, function(data) { /* ... */ });
This makes a request to /reports/123?other=123. data, in the callback, looks like { id: 123 }.

GET URL parameter from code in DNN 7.2

I want to get Full URL including URL Parameter in my module code.
For example
From This URL
http://Domain/Search-Space-For-Rent/Houston
TabController.CurrentPage.FullUrl
Gives me
//Domain/Search-Space-For-Rent
only I need to get last parameter from URL (Houston)
I also tried
Globals.NavigateURL(this.TabId, this.Request.QueryString["ctl"], UrlUtils.GetQSParamsForNavigateURL());
How can I get that?
So I regenerated URL using all query string parameters.
string path = TabController.CurrentPage.FullUrl;
foreach (string key in Request.QueryString.AllKeys)
{
if (key != "TabId" && key != "language" && key != "_escaped_fragment_")
{
if (key != null)
{
path += "/" + key + "/" + Request.QueryString[key];
}
else
{
path += "/" + Request.QueryString[key];
}
}
}
Typically within DNN you would simply get from the QueryString ex:
var myParam = Request.Querystring["paramName"];
What parameter name are you using when you build that URL? I would assume you've got a custom URL provider that changing something like "&city=Houston" to be /Houston instead. If that is the case, just grab the querystring paramter called City.
Update:
To get the "Name" of the page, assuming the scenario where Houston is a page in DNN, you could do the following.
var tc = new TabController();
var ti = tc.GetTab(TabId);
var pageName = ti.TabName
TabId comes from DNN, assuming your module inherits from PortalModuleBase you should have access to it. With that, you can then get the TabInfo from the TabController, and access the properties off that TabInfo object.

angularjs trying to understand and save a resource state with params

here's the relevant snippet of code:
$scope.submit = function() {
console.log(this);
weekly_habits = $resource('/api/users/:user_id/weekly_habits/:id/', {user_id: '#user'});
entry = weekly_habits.save({name: $scope.newAccomp, count: 0});
$scope.accomplishments.unshift(entry);
$scope.newAccomp = '';
}
my error is that no route matches /api/users/weekly_habits... My project is built in rails and I don't understand what this line means {user_id: '#user'}. Where is this #user object supposed to be? It would be much appreciated if someone explained what's going on here.
Thanks!
From the documentation:
If the parameter value is prefixed with # then the value of that parameter is extracted from the data object (useful for non-GET operations).
And later on they have an example
var User = $resource('/user/:userId', {userId:'#id'});
So the second argument to the resource service are the default parameters. In this case, by default, the userId will be extracted from the resource object you call a method on.
Previously I had an example of a GET operation, which doesn't really make sense in this case. But imagine you were doing a POST ($save) request with a data object. Angular would automatically extract the userId from the data object and inject it into the URL for you. You don't have to manually specify the value for the URL.
More info can be found on the doc page.
http://docs.angularjs.org/api/ngResource.$resource
Quoting the documentation: "If the parameter value is prefixed with # then the value of that parameter is extracted from the data object (useful for non-GET operations)."
The '#user' tells Angular to extract the value of user_id from the 'user' property of the object. So if you call .save() on an object that has an 'user' property of 'abc123', then the :user_id in your URL will be replaced with 'abc123'.

Resources