I am making an API POST call in Angular 8. I have to send a JSON object in the call which should be of structure:
-{}JSON
-{}data
-[]exp
+{} 0
+{} 1
but I am sending data in this format:
-[]JSON
+{} 0
+{} 1
in my typescript I am getting two objects {}0, {}1 in array called: receivedData then I am storing the data like:
this.changedData = this.receivedData;
this.postService.postMethod(this.headers, this.changedData)
in my postService:
postMethod(header, changedData): Observable<any[]> {
return this.http.post<any>(`the url here`, changedData, {headers: header, responseType: 'text' as 'json'})
.pipe(map(response => {
return response;
}))
}
how to send data in the mentioned format? I want the json structure of changedDetails to be as mentioned on the top with the same naming convention like: {}data and []exp How can I push receivedData objects into exp[] which I can then send into data{} which will then be entirely pushed into changedDetails {}
Just so we're on the same page, I'm imagining you're receiving data with the following shape:
[ { ... }, { ... } ]
And you want to transform it to this shape:
{
data: {
exp: [ { ... }, { ... } ]
}
}
(Let me know if this is not the case.)
If this is correct, than the transformation is quite straightfoward: simply create a new object literal like so:
this.changedData = {
data: {
exp: this.receivedData,
},
};
Related
I am working on an mobile app that should have a RadListView UI component filled with JSON data procured from an HTTP request. The JSON data that is at the URL address looks like this:
{"dataset": {
"table": [
{
"CustomerNumber": 1,
"Name": "Rudy",
}
}
}
All I get when I try to fill my RadListView with the data is "object Object" times the number of size parameter I request in the URL.
This is how I am trying.
ngOnInit() {
getJSON("http://192.168.10.18:8100/web/data?be=customer&size=5").then(
(r: any) => {
this._dataItems = new ObservableArray(r.dataset.table);
console.log("test: " + r.dataset.table[1]); // test: [object Object]
console.log("test2: " + this._dataItems.length); // test2: 5
},
(e) => {
console.log(e);
}
);
}
Any help is really appreciated as I have been stuck on this for a while and don't really know where to start.
I am trying to parse an array inside an object. I tried to map the result to get the array but could not reach to the point of the array.
My JSON looks like this.
{
"id": 1,
"projectName": "Opera house",
"projectDescription": "This image was taken during my first photography course.",
"thumbnailImageName": "1.JPG",
"projectDetails": {
"id": 1,
"relatedPhotos": [
"1.JPG",
"2.JPG",
"3.JPG"
],
"location": "Sydney",
"scope": "Learn basic of photography",
"description": "Some description"
},
"favouriteProject": true
}
And I am mapping the HTTP response from a server like this.
this.projectService.getProjectDetailsByProjectName(projectName).subscribe(res =>
{
Object.keys(res).map(key => {
this.projectDetails = res[key];
})
});
The above mapping gives me the projectDetails object but cannot access the array inside it. While accessing the array, I get output three times. Two times undefined and finally the actual value. Can anyone guide me how to parse the above JSON file properly?
Thank you very much..
************Edited code****************
My code to get the http response and parse each object is as follows:
getSelectedProjectWithDetails(){
const projectName:string = this.activatedRoute.snapshot.paramMap.get("project-name");
this.projectService.getProjectDetailsByProjectName(projectName).subscribe(res => {
// console.log(res.relatedPhotos);
Object.keys(res).map( (key, value) => {
this.projectDetails = res[key];
console.log(this.projectDetails["relatedPhotos"])
})
})
}
I have project interface as
export interface project{
id:number;
projectName: string;
projectDescription: string;
favouriteProject: boolean;
thumbnailImageName: string;
projectDetail: projectDetail;
}
and projectDetails interface as:
export interface projectDetail{
id: number;
relatedPhotos: String [];
location: string;
scope: string;
description: string;
}
and http get request is
getProjectDetailsByProjectName(projectName: String): Observable<project>{
return this.http.get<project>("http://127.0.0.1:8080/project/"+projectName);
}
As an alternate you can user JSON.parse(res); after you have mapped your response from observable.
like this
Object.keys(res).map(key => {
JSON.parse(res);
this.projectDetails = res[key];
})
However I am using res.json();
addNewProduct(data: any): Observable<string> {
return this._http.post(this.addNewProdUrl, data).map(res => res.json());
}
Not sure what is the issue with your res.
You can use map() to transform HttpResponse body to JSON using json() method. Since response contains body, headers etc. json() can be used to only parse body.
Please look into below code to understand the same.
this.http.get('https://api.github.com/users')
.map(response => response.json())
.subscribe(data => console.log(data));
To know more, please refer documentation
With the help of the forum I was able to get my httpclient observable mapping issue sorted with this syntax;
this._http.get<DomainMetaData>(serviceURL);
which works great! However, I have a json response coming back from the server which is nested and wonder if I can use the same syntax as I'm currently using or if I need to now manually .map the response into my classes?
Based on posts I've seen here on SO I've created two classes to represent the nested structure of the response JSON (see below).
The function call...
getDomainMetaData(domain): Observable<DomainMetaData> {
let serviceURL = "http://localhost:3000/selectdomains?domain=" + domain;
return this._http.get<DomainMetaData>(serviceURL);
}
The classes...
export class DomainMetaDataAttr {
constructor(public name: string,
public value: string) {
}
}
export class DomainMetaData {
constructor(public name: string,
public attributes: DomainMetaDataAttr[]) {
}
}
An example of the json...
//DomainMetaData
// {
// "ResponseMetadata": {
// "RequestId": "11f000bf-0dff-8a2a-31ff-8631a9f25b5b",
// "BoxUsage": "0.0008183545"
// },
// "Items": [
// {
// "Name": "2",
// "Attributes": [
// {
// "Name": "Document Date",
// "Value": "22/03/13"
// },
// {
// "Name": "Document Ref",
// "Value": "Doc test"
// }
// ]
// },
I love the neatness and simplicity of my current solution but I appreciate I may now have to change my code!
Many Thanks.
If I understand correctly you want to know how to use the JSON response from an HttpClient call.
I currently approach it like this:
// x.service.ts
getData() {
return this.http.get(URL);
}
// x.component.ts
this.service.getData().subscribe(res => {
if (res['data']) {
const data = res['data'];
// do whatever with the data
}
});
With the above approach you can run whatever methods / filters you want on the JSON e.g. map over the array and pull data out / mutate it, etc. Not sure if it's necessary to create additional classes to deal with the nested JSON data.
Oops! The code I posted actually works, I just wasn't referencing the results in the attributes array correctly.
Thanks for taking the time to look at this.
In my Angular RC2 app I make an observable HTTP call that returns the following JSON to me from the API:
{
"success":true,
"data":
{
"Type": 1
"Details":{
"Id":"123",
"Name":"test",
"Description":"test"
}
}
}
I map the data like this:
this._myService.get(id)
.subscribe(
(data) => {
this.details = data.Details;
this.type = data.Type;
},
(error) => {
this.setError(error);
}
);
How do I access the values inside the "Details" object from here?
I tried:
{{details.Name}}
But that won't work and I can't use ngFor to loop it either.
You could use the Elvis operator for this:
{{details?.Name}}
As a matter of fact, you load your data asynchronously so details is undefined at the beginning.
I have a $resource called Livres I need to send to my API that wait a json typed like this :
{livres: {
id: 1
name: "bidule"
}}
This is the resource :
angular.module('TestApp').factory('Livres', [
'$resource', function($resource) {
return $resource('api/v1/livres/:id', {
id: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
And the called method to save :
$scope.addLivres = function() { //create a new livres. Issues a POST to /api/livress
$scope.livres.$save(function() {
$state.go('adminLivres'); // on success go back to admin home i.e. adminLivres state.
});
};
This only send a json like
{id: 1
name: "bidule"}
How can I make the json send to be encapsulated into a livres {} ?