Render HTTP-Response as a list in Angular2 - json

I have a json response like this.
{
"response": {
"data": {
"customers": [{
"customerNumber": "123",
"customerName": "ABC",
"customeraddresse": [{
"address": "test"
}]
}, {
"customerNumber": "345",
"customerName": "CDS",
"customeraddresse": [{
"address": "test1"
}]
}]
}
}
}
I am doing a request like this to get the response data. And it will be returned, as I already checked.
public getData(): Promise<any> {
let payload = JSON.stringify( ... );
let headers = new Headers({ 'Content-Type': 'application/json'});
return this.http.post(this.url, payload, { headers: headers })
.toPromise()
.then(res => {
this.response_data = res.json().response.data;
return this.response_data;
})
.catch(this.handleError);
}
But the problem is, that I want to get the value of customerNumber and customerName, and display them in a list
In this example, there are two customers, so this markup should be rendered two times:
<div>
<div>CustomerNumber</div>
<div>CustomerName</div>
</div>

You should use an *ngFor loop.
In your template:
<div *ngFor="let customer of response_data.customers">
<div>{{customer.customerNumber}}</div>
<div>{{customer.customerName}}</div>
</div>

Related

How to ignore a variable in JSON data in Angular TypeScript

I am facing a problem while reading a JSON file in angular 7.
below is the format of my JSON data file.
[
{
"attributes": {
"User": "jay"
}
},
{
"attributes": {
"User": "roy"
}
},
{
"attributes":{
"User": "kiya"
}
},
{
"attributes":{
"User": "gini"
}
},
{
"attributes": {
"User": "rock"
}
},
{
"attributes": {
"User": "joy"
}
}
]
here is my component.ts file method in which I am calling service for a JSON file.
this.rest.getUsers().subscribe((data: {}) => {
console.log(data);
this.items = data;
//this.items=data;
});
Here is my service.ts file method.
private extractData(res: Response) {
let body = res;
return body || { };
}
getUsers():Observable<any> {
return this.httpService.get('./assets/usersdetails.json').pipe(
map(this.extractData));
}
Now I want to read only User from the JSON file and I want to filter the word attributes. is there any way to filter this thing from JSON file, so that I can only get the User value. because in my Project this attributes in JSON is creating a problem and I want to ignore or filter this.
because in my application I need to read the JSON as below format.
[
{
"User": "jay"
},
{
"User": "roy"
},
{
"User": "kiya"
},
{
"User": "gini"
},
{
"User": "rock"
},
{
"User": "joy"
}
]
but the data is coming in the format as above mentioned JSON format with attributes
so is there any way to filter the extra attributes thing from the JSON at the time of reading.
You don't show the code for the extractData method, so it is hard to say what isn't working there, but you should be able to accomplish your goals with the following.
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => d.attributes))
);
If there are other properties on 'attributes' and you really only want the 'user' data, then you could further update the code to:
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => ({ 'User': d.attributes.User })))
);

Angular Typescript access specific JSON object by id in an observable

I have this json string below and I want to either pull the "stocks" data array or the "contacts" data array based on whichever one I need for a given request:
[{
"id": "stocks",
"name": "Stocks",
"data": [
{
"id": 1,
"name": "Actuant Corporation",
"symbol": "ATU"
},
{
"id": 2,
"name": "Xilinx, Inc.",
"symbol": "XLNX"
}
]
},
{
"id": "contacts",
"name": "Contacts",
"data": [
{
"id": 1,
"full_name": "Betty Traise"
},
{
"id": 2,
"full_name": "Hank Hurrion"
},
{
"id": 3,
"full_name": "Calvin Ommanney"
}
]
}]
For example, in the function below, which is an observable, assume the payload argument is "contacts". In that case, I need to return the "id: "contacts" data array. Here's the code I'm using:
loadData$(payload: any = {}): Observable<any> {
// paths: {
// titlemaps: 'http://localhost:4100/data'
// },
// return this.service.get(this.config.paths.titlemaps, payload);
const JSON: any = this.service.get(this.config.paths.titlemaps, payload);
console.log('payload: ' + payload, 'json: ' + JSON); // if payload is "contacts", return only the contacts
return JSON.find(data => data.id === 'contacts');
}
The console log returns "contacts" and the entire JSON as expected. However, the JSON.find fails with error:
ERROR TypeError: JSON.find is not a function
When I switch the function types a bit, I get typescript compiler error:
[ts] Property 'find' does not exist on type 'Observable'.
What am I missing?
The result of your service call seems to be an observable, you can transform the result and return a new value with rxjs pipeable operators:
import { map } from 'rxjs/operators';
....
loadData$(payload: any = {}): Observable<any> {
return this.service.get(this.config.paths.titlemaps)
.pipe(
map(result => result.find(data => data.id === payload))
);
}
Hope it helps!
I moved the mapping/find operation to the service since you're passing those as params but you don't have to do it like that of course...
https://stackblitz.com/edit/angular-2lajx4
The gist...
get(url, payload) {
return of(results)
.pipe(map((res: any) => {
return res.find(data => data.id === payload)
}));
}
Just using of() here to simulate an observable, results is the JSON you provided above...
loadData$ subs to the get and puts the data into a variable for consumption
data: any;
loadData$(payload: any = {}) {
this.service.get('../results.json', payload).subscribe(data => {
this.data = data
console.log('payload: ' + payload, 'json: ' + this.data); // if payload is "contacts", return only the contacts
});
}

I want to get Affinity Interest from Google analytics api v4

I put the tracking code of google analytics in my web Application, now i want to get the Interests of the user from Google analytics API, I am using Nodejs, here is my request's code and the JSON response I get.
const dimensions_rows = [{
name: 'ga:interestAffinityCategory'
}, ];
const date_filters = [{
startDate: '7daysAgo',
endDate: 'today',
}];
const req = {
reportRequests: [{
viewId: viewId,
dateRanges: date_filters,
dimensions: dimensions_rows,
}],
};
analytics.reports.batchGet({
auth: oauth2Client,
requestBody: req
},
function(err, response) {
if (err) {
console.log('Failed to get Report');
console.log(err);
return;
}
// response.data is where the good stuff is located
console.log('Success - got something back from the Googlez');
console.log("responseee: ", JSON.stringify(response.data));
}
);
//JSON response
{
"reports": [{
"columnHeader": {
"dimensions": ["ga:interestAffinityCategory"],
"metricHeader": {
"metricHeaderEntries": [{
"name": "ga:visits",
"type": "INTEGER"
}]
}
},
"data": {
"totals": [{
"values": ["0"]
}]
}
}]
}

send header with put request node.js

var request=require('request');
var values = [
{
"id": "24",
"kind": "nature",
"data": {}
}
]
request.put("http://localhost:5000/api/article/",values,function (err,data,res) {
res=JSON.parse(res)
console.log(res)
})
I think it's kinda obvious what I'm trying to do here. Can someone please tell me what I'm doing wrong?? If I'm verry far of can someone set me on the right track?
var request = require('request');
var values = [
{
"id": "24",
"kind": "nature",
"data": {}
}
];
request({
method: 'PUT',
url: 'http://localhost:5000/api/article/',
body: values,
json: true,
headers: {
'User-Agent': 'request'
}
}, (err, res, body) => {
// ...
});
See the docs: https://www.npmjs.com/package/request#custom-http-headers

Angular2, get data from REST call

I'm triyng to get data from json file by a id, by I'm getting all the content.
Here the JSON:
[
{ "id": "1", "name": "Carlos", "apellidos":"López", "edad":"30", "ciudad":"Hospitalet" },
{ "id": "2", "name": "Arantxa", "apellidos":"Pavia", "edad":"24", "ciudad":"Barcelona" },
{ "id": "3", "name": "Didac" , "apellidos":"Pedra", "edad":"muchos", "ciudad":"Cornellà" },
{ "id": "4", "name": "Daniel" , "apellidos":"Farnos", "edad":"nolose", "ciudad":"Barcelona" }
]
Service:
private usersUrl = 'app/users.json';
getUser(id: String): Observable<User>{
let body = JSON.stringify(
{
"token": "test",
"content": {
"id": id
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers,
body : body
});
return this.http.get(this.usersUrl, options)
.map(res => res.json()).catch(this.handleError);
}
Angular Component:
ngOnInit(){
this.route.params.subscribe(params => {
let id = +params['id'];
this.apiService.getUser(id).subscribe( (res) => { console.log(res); } );
})
}
Console.log:
Array[4]0: Object1: Object2: Object3: Objectlength: 4__proto__: Array[0]
Is the JSON bad?
Thanks.
Because you didn't filter the result by id.
.map(res => res.json())
.map(x > x.find(x => x.id == id) // filter by selected id
.catch(this.handleError);