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

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

Related

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

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"]
}]
}
}]
}

React Native render nested Json

After loading a JSON object and adding it to this.state, I am not able to access levels below the first level. Given this JSON file:
{
"ts": 1530703572,
"trend": {
"val": 0,
"text": "gleichbleibend"
},
"baro": 1011.3453734999999,
"temp": {
"out": {
"f": 85.9,
"c": 29.9
}
},
"hum": {
"out": 28
},
"wind": {
"speed": {
"mph": 2,
"kmh": 3.2
},
"avg": {
"mph": 3,
"kmh": 4.8
},
"dir": {
"deg": 192,
"text": "SSW"
}
},
"rain": {
"rate": 0,
"storm": 0,
"day": 0,
"month": 0,
"year": 451.358
},
"et": {
"day": 88,
"month": 81,
"year": 1802
},
"forecast": {
"val": 6,
"rule": 45,
"text": "Zunehmend wolkig bei gleichbleibender Temperatur."
},
"sun": {
"uv": 6.2,
"rad": 779,
"rise": "4:27",
"set": "20:35"
}
}
the following results:
{this.state.weatherList.ts} works: 1530703572
{this.state.weatherList.temp.out.c} "TypeError: Undefined is not an object (Evaluating: 'this.state.weatherList.temp.out')
The Code:
export default class Weather extends React.Component {
constructor(props) {
super(props)
this.state = {
weatherList: []
}
getPlannerData().then(data => {
this.setState({
weatherList: data
})
})
}
return (
<ScrollView>
<View>
<View>
<Text>{this.state.weatherList.temp.out.c}</Text>
</View>
</View>
</ScrollView>
)
}
}
async function getPlannerData() {
let data = await fetchApi('url')
return data
}
async function fetchApi(url) {
try {
let response = await fetch(url)
let responseJson = await response.json()
console.log(responseJson)
return responseJson
} catch (error) {
console.error(error)
return false
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22
},
sectionHeader: {
paddingTop: 2,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 2,
fontSize: 14,
fontWeight: 'bold',
backgroundColor: 'rgba(247,247,247,1.0)'
},
item: {
padding: 10,
fontSize: 18,
height: 44
}
})
The question is how I can alter the code, so I can access the nested elements like "temp".
I tried it with renderItem and {this.state.weaetherList.map((item, i) => without success.
Thanks in advance!
Before your weatherList object is set, anything further than one level down your object will result in an error. this.state.weatherList.ts will not give an error, since it will just be undefined before your request is finished.
You could e.g. keep a state variable loading and only render when you request has finished to get around this.
Example
class Weather extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
weatherList: {}
};
getPlannerData().then(data => {
this.setState({
loading: false,
weatherList: data
});
});
}
render() {
const { loading, weatherList } = this.state;
if (loading) {
return null;
}
return (
<ScrollView>
<View>
<View>
<Text>{weatherList.temp.out.c}</Text>
</View>
</View>
</ScrollView>
);
}
}

Angular map function is returning "undefined is not a function"

I'm following this tutorial https://www.barbarianmeetscoding.com/blog/2016/04/02/getting-started-with-angular-2-step-by-step-6-consuming-real-data-with-http/, with Angular2 and VS Code.
I created a db.json server to test an api with, with the test data looking like
{
"articles": [{
"id": 1,
"name": "Wand of Lightning",
"description": "A powerful wand of ligthning.",
"price": 50,
"imageUrl": "/assets/images/wand.png",
"specs": [{
"name": "weight",
"value": 10
}, {
"name": "height",
"value": 22
}, {
"name": "material",
"value": "wood"
}],
"reviews": [{
"author": "Jaime",
"title": "I loved it!",
"content": "I loved the wand of ligthning! I usually use it to charge my laptop batteries!",
"rating": 5
}, {
"author": "John Doe",
"title": "Underwhelming",
"content": "I didn't like it at all...",
"rating": 1
}]
}, {
"id": 2,
"name": "Staff of Fire",
"description": "A powerful staff of fire.",
"price": 150,
"imageUrl": "/assets/images/staff-of-fire.png",
"specs": [{
"name": "weight",
"value": 10
}, {
"name": "height",
"value": 22
}, {
"name": "material",
"value": "wood and alabaster"
}],
"reviews": [{
"author": "Jaime",
"title": "I loved it!",
"content": "I loved the wand of ligthning! I usually use it to charge my laptop batteries!",
"rating": 5
}, {
"author": "John Doe",
"title": "Underwhelming",
"content": "I didn't like it at all...",
"rating": 1
}]
}
Now if I try to adapt my code to the sample, I get
undefined is not a function
Here's items.component.ts
import { Component, OnInit } from '#angular/core';
import {ItemsService} from '../items.service';
import {Item} from '../item';
#Component({
selector: 'app-items',
templateUrl: './items.component.html',
styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {
items: Item[] = [];
errorMessage: string = '';
isLoading: boolean = true;
constructor(private itemsService: ItemsService) { }
ngOnInit() {
this.itemsService
.getAll().
subscribe(
p => this.items =p,
e => this.errorMessage = e,
/* onCompleted */ () => this.isLoading = false
)
}
}
items.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import {Item} from './item';
#Injectable()
export class ItemsService {
private baseUrl: string ='http://localhost:3000';
constructor(private http: Http) {
}
getAll(): Observable<Item[]>{
let items = this.http
.get(`${this.baseUrl}/articles`, { headers: this.getHeaders()})
.map(this.mapItems)
.catch(this.handleError);
return items;
}
private getHeaders(){
let headers = new Headers();
headers.append('Accept', 'application/json');
return headers;
}
mapItems(response:Response): Item[]{
return response.json().map(this.toItem)
}
toItem(r:any): Item{
let result = <Item>({
id: r.id,
name: r.name,
description: r.description,
price: r.price,
imageUrl: r.imageUrl,
});
console.log('Parsed item:', result);
return result;
}
// this could also be a private method of the component class
handleError (error: any) {
// log error
// could be something more sofisticated
let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
console.error(errorMsg);
// throw an application level error
return Observable.throw(errorMsg);
}
}
Note: making
return response.json().map(this.toItem)
Into
return response.json()
works. But I would like to get map working.
EDIT: Screenshot
this will solve your issue -
getAll(): Observable<Item[]> {
const items = this.http
.get(`${this.baseUrl}/articles`, {headers: this.getHeaders()})
.map((response: Response) => this.mapItems(response.json()))
.catch(this.handleError);
return items;
}
mapItems(data: Array<any>): Item[] {
return data.map(item => this.toItem(item));
}
I think what you want to map (Array.prototype.map) is the articles in your response object, and not the object itself. Do this:
mapItems(response:Response): Item[]{
return response.json().articles.map(this.toItem)
}

how can i get string json in angular2

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