Restangular post - angularjs

I am trying to use restangular in my project, I have the set up and config all working fine.
I need to make a post request where i have the url and a json payload.
var url = xyz.com + "/api/v2/create?type=project";
eg payload
'{
"class":"Project",
"name":"test_project",
"description":"test_project",
"owner":{"class":"User","id":"2"},
"connection":{"class":"Connection","id":"1"},
"defaultNamespace":"default",
"namespaces":["default"]}'
I was unsure of how to make a restangular call, should the post have the payload as params?
I tried this below, but did not seem to work.
Restangular.all('create').post({
"class":"Project",
"name":"test_project",
"description":"test_project",
"owner":{"class":"User","id":"2"},
"connection":{"class":"Connection","id":"1"},
"defaultNamespace":"default",
"namespaces":["default"]})

Hey you should do something like:
Restangular.all('create').post(
// First the object
{
class: "Project",
name: "Test-project",
owner: {
class: "User"
}
},
// Then the request params
{type: "Project"}
);
That should do it :)

Related

How to post data when you have javascript object using multipart/form-data content-type

So I have never post a data using FormData and multipart/form-data as Content-Type in my React project. But now I'm kinda forced by backend to send it this way since we have some images in payload.
The problem is that the whole data is a JS object and can be parsed to JSON, and nothing more. So how can I convert my JS object into a valid FormData that backend would accept it? Everything works without a problem in Postman, but in the app I always get the same error.
Here is some more detail:
The working Postman sample:
What I expect to be working (but obviously doesn't):
const createProd = () =>
HttpRequest.post('/api/prod', {
body: {
Product: {
title: 'Test Prod',
shop: null,
description: "My new ad's description",
category: { id: '5d8c6aa6fadeaf26b0194667' },
condition: 'USED'
}
});
HttpRequest is a helper function which uses ES6 fetch for requests.
I always get the same error: "Required request part 'Product' is not present" with/without JSON.stringify.
I even tried to create a sample FormData to at least change the error:
cont payload = new FormData();
payload.append('Product', {foo: 'bar'});
But still same error. I also copied the code which is generated by Postman. But still no chance.
I would be thankful if you share your suggestions or workarounds.
Thanks in advance.
const formData = new FormData();
const product = { //your product object };
formData.append('product', JSON.stringify(product));
const config = {
headers: {
'Content-Type': 'multipart/form-data; charset=utf-8; boundary="another cool boundary";'
}
};
axios.post(`/api/ads`, formData, config).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
});
Maybe you should set header.
Try this one. In my case I used Axios. It worked for me in my project.

Angular 2 http get querystring params

Hopefully someone can help with this. I building an ionic 2 app which is based on the newer Angular 2, I am familiar with previous versions of Angular, but still trying to figure this whole typescript.
I have my API setup with basic get querystrings (e.g domain.com?state=ca&city=somename)
export class TestPage {
public state: string ='ca';
public city: string = null;
constructor(private http: Http){}
public submit() {
let url = "http://localhost/api";
let payload = {"state": this.state, "city": this.city};
this.$http.get(url, payload).subscribe(result => {
//result
}, err => {
//do something with the error
}
)
}
}
When I execute this it pulls my API url fine and I can get a response back, however none of the querystrings are being sent in the request. Its just sending http://localhost/api. If I console.log the payload its fine.
Ultimately I am trying to get it to do https://localhost/api?state=ca&city=example
Looking at examples I can't really find anything straight-forward on this.
Is it not possible to take a payload on http with this newer version of Angular? The code above is just an example. I have many querystrings, which is why I was hoping to send a payload to it.
Any help or suggestion would be appreciated.
The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.
The search field of that object can be used to set a string or a URLSearchParams object.
An example:
// Parameters obj-
let params: URLSearchParams = new URLSearchParams();
params.set('state', this.state);
params.set('city', this.city);
//Http request-
return this.http.get('http://localhost/api', {
search: params
}).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
Documentation: here

Make GET call to REST service with parameters in Angular 2

I am trying to make a GET call to the YouTube Web API but I cannot figure out how to pass parameters using the http.get function. I have used fiddler and made sure the request is being made. I am currently getting a 400 error saying that I am missing a the parameter "Part". How can I modify my code to include the required parameters in my request?
private _url = 'https://www.googleapis.com/youtube/v3/';
private _key = '';
getPlaylistVideos(playlistId, pageToken){
var url = this._url + "playlistItems";
var options = { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken }
return this.http.get(url, options);
}
You need to include the search params in to your request. I think this will work for you:
getPlaylistVideos(playlistId, pageToken) {
let url = `${this._url}playlistItems`,
options = { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken },
params = URLSearchParams();
for (let key in options) params.set(key, options[key);
return this.http.get(url, {search: options});
}
You create the URLSearchParams using the set method you can find the full documentation here
Please have a look at the already asked & solved question regarding AngularJS & YouTube V3 API. See here thanks to #Sandeep Sukhija.
Anyhow, about the missing parameter part, add it to the request ex: part: 'snippet'
Example code :
function getPlaylistVideos(playlistId, pageToken) {
// pass the page token as a parameter to the API
$.get('https://www.googleapis.com/youtube/v3/playlistItems', { part: 'snippet', maxResults: 50, playlistId: playlistId, key: key, pageToken: pageToken })
}
How to use the part parameter
The part parameter is a required parameter for any API request that
retrieves or returns a resource. The parameter identifies one or more
top-level (non-nested) resource properties that should be included in
an API response. For example, a video resource has the following
parts:
snippet contentDetails fileDetails player processingDetails
recordingDetails statistics status suggestions topicDetails

How to paginate if no page token present in Youtube API search request

I'm querying videos to Youtube API with AngularJS this way:
$http.get('https://www.googleapis.com/youtube/v3/search', {
params: {
key: 'API_KEY',
type: 'video',
part: 'id,snippet',
maxResults: '10',
fields: 'items/id,items/snippet/title,items/snippet/description,items/snippet/thumbnails/default,items/snippet/channelTitle',
q: query
}
}
However, the response object is only returning a JSON response with items property but there's not a nextPageToken or pageInfo properties.
I need to obtain multiple results, so it's pretty important to me to be capable to paginate the search.
I already tried with out maxResults query param but got not results. How can I achieve it?
I was trimming the API answer to myself:
fields: 'items/id,items/snippet/title,items/snippet/description,items/snippet/thumbnails/default,items/snippet/channelTitle'
So the fields param is the one telling API which response properties to include.

Add parameters to query string when using PUT method with Angular's $http

I'm using Angular's $http service to make web api requests. When I use the GET method, the two param values are added to the query string:
// http://foo.com/api/test?heroId=123&power=Death+ray
$http.get("/api/test", {
params: { heroId: 123, power : "Death ray" }
})
However, when I use the PUT method the params are JSON-encoded and sent as the request payload:
// {"params":{"heroId":123,"power":"Death ray"}}
$http.put("/api/test", {
params: { heroId: 123, power : "Death ray" }
})
How can I force the params to be added to the query string when using PUT?
With $http.put, $http.post or $http.patch, the config object containing your url parameters goes as the third argument, the second argument being the request body:
$http.put("/api/test", // 1. url
{}, // 2. request body
{ params: { heroId: 123, power : "Death ray" } } // 3. config object
);
$http.put documentation for reference
AngularJS send json data and not x-www-form-urlencoded format data.
Though you can try the below one:
$http.put("/api/test", { heroId: 123, power : "Death ray" });
If your api url is "api/test/heroId/power",
var data = 123+'/Death ray'
$http.put("api/test"+data);

Resources