how can i get string json in angular2 - json

in my angular2 component
keyword_test={};
getData() {
this.service.getData()
.subscribe(
data => {
this.keyword_test = data
console.log(data);
console.log(this.keyword_test);
});
}
console.log(data) and console.log(this.keyword_test) print right data like this
{
"caption": "folder0",
"type": "folder",
"subnodes": [
{
"caption": "folder1",
"type": "folder",
"subnodes": [
{
"caption": "keyword1",
"type": "keyword",
"search_filter_expression": "sfe1"
},
{
"caption": "keyword2",
"type": "keyword",
"search_filter_expression": "sfe2"
}
]
},
{
"caption": "folder2",
"type": "folder",
"subnodes": [
{
"caption": "keyword3",
"type": "keyword",
"search_filter_expression": "sfe3"
},
{
"caption": "keyword4",
"type": "keyword",
"search_filter_expression": "sfe4"
}
]
}
]
}
but in my ngOnInit
ngOnInit() {
this.getData();
console.log(this.keyword_test);
}
despite the this.getdata(), this.keyword_test print "Object {}" i think none object.
Is the keyword_test initialized incorrectly?
when i print console.log(typeof data) in getData function, result is string...
I did change it to json in service, but I do not know why.
++and this is my service
#Injectable()
export class keywordService {
private API_URI: string = 'MYAPIURL';
constructor(private http: Http) {
}
getData() {
return this.http.get(this.API_URI, {body: ""})
.map(res => {res.json();
});
}
}

ngOnInit() {
this.getData(); // this execute but data arrives with call back
console.log(this.keyword_test); //this execute before data has arrived and thats why it is not printing the result from success call
}
Correct way
this.service.getData()
.subscribe(
data => {
this.keyword_test = data
console.log(data);
console.log(this.keyword_test);
});

Related

Getting .map() not a function when trying to pass JSON to Vue

I have created a api on my backend and have the result in JSON on http://localhost:5000/result. I figured out that I need a .js file that will handle the api and allow me to use the data in my Vue components. This is the solution I found:
import axios from 'axios';
const url = "http://localhost:5000/result";
class WeatherService {
static getWeather() {
return new Promise((resolve, reject) => {
axios.get(url).then((res) => {
try {
const data = res.data;
resolve(
data.map(weather => ({
...weather
}))
);
} catch (error) {
reject(error);
}
})
})
}
}
export default WeatherService;
My Vue component
<script>
import WeatherService from '../WeatherService';
export default {
name: 'Result',
data(){
return {
weather: [],
error: ''
}
},
async created() {
try {
this.weather = await WeatherService.getWeather();
} catch (error) {
this.error = error.message;
}
}
}
</script>
Once I start up both, I get data.map is not a function and am not able to utilize any of the data.
Edit: I'm realizing now that .map() is used on arrays, and I'm trying to use it on JSON data. What would be a comparable solution?
Edit 2: Json data
{
"coord": {
"lon": -97.7431,
"lat": 30.2672
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 82.15,
"feels_like": 81.23,
"temp_min": 80.01,
"temp_max": 84.2,
"pressure": 1015,
"humidity": 37
},
"visibility": 10000,
"wind": {
"speed": 3.44,
"deg": 0
},
"clouds": {
"all": 1
},
"dt": 1614206313,
"sys": {
"type": 1,
"id": 3344,
"country": "US",
"sunrise": 1614171738,
"sunset": 1614212779
},
"timezone": -21600,
"id": 4671654,
"name": "Austin",
"cod": 200
}
The data you need doesn't require any mapping, so the Axios callback should just resolve the API response as-is:
class WeatherService {
static getWeather() {
return new Promise((resolve, reject) => {
axios.get(url).then((res) => {
resolve(res.data);
})
})
}
}
Note that axios.get() already returns a Promise, so you could just return that without wrapping it:
class WeatherService {
static getWeather() {
return axios.get(url).then(res => res.data)
}
}

Angular unable to display API results in html

In Angular, why am I unable to display the results from an API call?
The JSON returned from the API call. I want to display the value attribute.
{
"data": [
{
"type": "fuzzycompletions",
"attributes": {
"value": "APALE"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "9695006WHN4DWDKBF403"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/9695006WHN4DWDKBF403"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLITEC"
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "AppLogic"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "724500S2JQ8M9Q67N911"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/724500S2JQ8M9Q67N911"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPRECIO"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500ZFBM0TC2T1HV85"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500ZFBM0TC2T1HV85"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "AMPLEGEST"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500DYMLRK8URCGP47"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500DYMLRK8URCGP47"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "ANPLEX OÜ"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "254900RNJSFWJXOZE551"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/254900RNJSFWJXOZE551"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "Apleks OÜ"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "254900VZB706EXH22533"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/254900VZB706EXH22533"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLE-WAY"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500QV2N8IIVULLH93"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500QV2N8IIVULLH93"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLICOMM"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500MCJ58VYVTX3715"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500MCJ58VYVTX3715"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLIQ AS"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "8945006S1SZMS8HKLR20"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/8945006S1SZMS8HKLR20"
}
}
}
}
]
}
I have a service.ts file for connecting to the API
import { HttpClient} from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class GleifService {
private gleifUrl = 'https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalName&q='; // URL to web api
private data:any = []
constructor(private http: HttpClient) {}
getGleif(name: string){
const url = `${this.gleifUrl}${name}`;
this.http.get(url).subscribe((res)=>{
this.data = res
console.log(this.data)
})
}
}
A component.ts file
import { Component, OnInit } from '#angular/core';
import { GleifService } from '../gleif.service';
#Component({
selector: 'app-security',
templateUrl: './security.component.html',
styleUrls: ['./security.component.css']
})
export class SecurityComponent implements OnInit {
// array for storing the data
private data:any = []
constructor(private gleifService: GleifService) { }
getGleif(name: string): void {
this.data = this.gleifService.getGleif(name);
}
ngOnInit() {
this.getGleif(name);
}
}
And a .html file for displaying the results
<div>
<label>Company ID:
<input placeholder="Autofill"/>
</label>
</div>
<div>
<label>Company Name:
<input #Name placeholder="A Company Ltd"/>
<button (click)="getGleif(Name.value); Name.value=''">Search</button>
</label>
</div>
<div *ngFor="let entry of data?.data" style="text-align:center">
<h3>
header works: {{ entry.type }}
</h3>
</div>
I can see the results in the console response. How can I access and display results from the API call?
It is because you are subscribing your http call from your service instead of returning it's data. Once you have subscribed the call in your service, no data will be returned unless you return the observable value from your http and let the component subscribe it's response or data
Update your code instead to:
Service
import { Observable } from 'rxjs';
...
getGleif(name: string): Observable<any> {
const url = `${this.gleifUrl}${name}`;
return this.http.get(url);
}
Component
...
getGleif(name: string): void {
this.gleifService
.getGleif(name)
.subscribe(res => this.data = res);
}
or in your Component you could also do this:
...
data$: Observable<any>;
getGleif(name: string): void {
this.data$ = this.gleifService.getGleif(name); // we have assigned it with an Observable variable since the return of this service is of Observable type that needed to be subscribe into
}
Template
...
// Since the data$ is async, we use pipe async to fetch it's raw data
<div *ngFor="let entry of (data$ | async)?.data" style="text-align:center">
...
</div>
make sure to return the data from the service and subscribe inside the component file.
and you don't need to call the function inside ngOnInit because you are going to call it when search button is clicked.
componet.ts file
import { Component } from "#angular/core";
import { GleifService } from "./service";
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
// array for storing the data
private data: any = [];
constructor(private gleifService: GleifService) {}
getGleif(name: string): void {
this.gleifService.getGleif(name).subscribe((response: any) => {
this.data = response.data;
});
}
}
component.html file
<div>
<label
>Company ID:
<input placeholder="Autofill" />
</label>
</div>
<div>
<label
>Company Name:
<input #Name placeholder="A Company Ltd" />
<button (click)="getGleif(Name.value); Name.value=''">Search</button>
</label>
</div>
<div *ngFor="let entry of data" style="text-align: center;">
<h3>
header works: {{ entry.type }}
</h3>
</div>
service.ts file
import { HttpClient } from "#angular/common/http";
import { Injectable } from "#angular/core";
#Injectable({
providedIn: "root"
})
export class GleifService {
private gleifUrl =
"https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalName&q="; // URL to web api
constructor(private http: HttpClient) {}
getGleif(name: string) {
const url = `${this.gleifUrl}${name}`;
return this.http.get(url);
}
}
working codesandbox
Maybe you need to subscribe to the result in the component.ts file
getGleif(name: string): void {
this.gleifService.getGleif(name).subscribe((result) => {
this.data = result
});
}

Retrieve data from json with multiple arrays?

I am having difficulties retrieving data from .json file in this format, I have tried headers, changing URL but it is not working:
{
"cars": ["BMW", "Mercedes", "Fiat"],
"testDrives": [
{
"start": "2020-02-03T11:00:00.000Z",
"end": "2020-02-03T16:00:00.000Z",
"name": "Bmw"
},
{
"start": "2020-02-03T09:00:00.000Z",
"end": "2020-02-03T12:30:00.000Z",
"name": "Mercedes"
}
]
}
My code:
data = '../../assets/test.json';
constructor(private http: HttpClient) { }
getData() {
this.http.get(this.data).subscribe(data => {
console.log(data);
});
}
I keep getting this error:
error
You need to define an interface with required properties to specify the response type
export interface ResponseModel{
cars: string;
testDrives: string;
}
and specify Response type in subscribe
getData() {
this.http.get(this.data).subscribe((data: ResponseModel) => {
console.log(data);
});
}

In a JSON file I need to access to an attribute name with ':' in it

I'm a react-native noob.
I need to read a link inside a JSON field called 'wp:featuredmedia.href'.
obviusly i can't put the ':' char in the code.
I've tried in this way... but I've no success :(
componentDidMount(){
const { navigation } = this.props;
const id = navigation.getParam('id', );
//const percorso = 'responseJson.wp:featuredmedia.rendered';
return fetch('https://www.seisnet.it/wp-json/wp/v2/posts/'+id)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
title: String(responseJson.title.rendered),
photos: String(responseJson.wp:featuredmedia),
}, function(){});
})
.catch((error) =>{
console.error(error);
});
}
EDIT 1
this is a section of the json file:
// 20190726085445
// https://www.seisnet.it/wp-json/wp/v2/posts/1967
"_links": {
"self": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts/1967"
}
],
"collection": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts"
}
],
"about": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/types/post"
}
],
"wp:featuredmedia": [
{
"embeddable": true,
"href": "https://www.seisnet.it/wp-json/wp/v2/media/1971"
}
],
"wp:attachment": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/media?parent=1967"
}
],
}
}
the field i've to read contains a link to another json file.
i've tried: JSONResponse_embedded["wp:featuredmedia"] and JSONResponse["wp:featuredmedia"]. the first give me the error "undefined is not an object" while the second give me nothing in output
Instead of responseJson.wp:featuredmedia, try responseJson["wp:featuredmedia"]
JavaScript object: access variable property by name as string

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 })))
);