0

I'm struggling by displaying data from a single JSON respone with angular. I've created a class for the data interndata.model.ts

export class Interndata {
humidity: number;
temperature: number;

constructor(humidity:number, temperature:number) {
    this.humidity = humidity;
    this.temperature = temperature;
  }

}

For this I crated a service interndata.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Interndata } from './interndata.model';
import { Observable } from 'rxjs';

@Injectable({
   providedIn: 'root'
})
export class InterndataService {

 constructor(private http: HttpClient){}

 public getDisplayData(): Observable<Interndata[]>{
       return this.http.get<Interndata[]>('http://192.168.0.110:8080/process');
      }
 }

My JSON response from the webservice is this:

{"humidity": 49.099998474121094, "temperature": 24.899999618530273}

The class AppComponent shall get then the data regulary and update ngx-gauge to display the data.

import { Component, OnInit } from '@angular/core';
import { NgxGaugeModule } from 'ngx-gauge';
import { HttpClient } from '@angular/common/http';
import { concatMap, map, merge, switchMap, tap, delay, skip } from 'rxjs/operators';
import { concat, of, Observable, BehaviorSubject, timer } from 'rxjs';
import { Interndata } from './interndata.model';
import { InterndataService } from './interndata.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})



export class AppComponent implements OnInit {

interndata = new Array<Interndata>();
title = 'Home Automation Monitor Service';
tempValue = 0;
humValue = 0;
gaugeType = "semi";
tempLabel = "Temperatur";
tempAppendText = "°C";
gaugeThick = 25;
gaugeForegroundColor = "#000000";
gaugeBackgroundColor = "#FFFFFF";
tempMin = 0;
tempMax = 30;
humLabel = "Luftfeuchtigkeit";
humAppendText = "%";
humMin = 0;
humMax = 100;
constructor(private servinterdata : InterndataService){
    servinterdata.getDisplayData().subscribe((res) => {
        this.interndata = res;
        console.log(this.interndata);
    });
}

ngOnInit () {

}

}

I do not know how I can use the data from the JSON response. Console.log returns the JSON as string.

this.interndata.humidity 

returns undefined. How can access the data I get from the JSON response?

12
  • did you check the developer tool and see what kind of respond do you get ? Commented Aug 16, 2019 at 21:03
  • console.log(res); what does print Commented Aug 16, 2019 at 21:04
  • You have typed of the response as an array Interndata[] perhaps this is what you want but in that case the json must be an array like this. [{"humidity": 49.099998474121094, "temperature": 24.899999618530273}] Commented Aug 16, 2019 at 21:08
  • 1
    If angular parses a single object correctly (no reason why they should but you never know :) access the data like so this.interndata[0].humidity Commented Aug 16, 2019 at 21:11
  • @NathanielJohnson the method mark as it s will return an array not a single object maybe [{}] is the result Commented Aug 16, 2019 at 21:14

2 Answers 2

1

If its returning a string, this.interndata = JSON.parse(res) should get you a nice javascript object. If that doesn't work, let me know and we can try something else.

Sign up to request clarification or add additional context in comments.

4 Comments

HttpClient class will parse the response by default 🤔🤔
Yeah that's what I was thinking but in the question they said "Console.log returns the JSON as string." which seemed odd but if that's the case, an easy fix. I'm wondering if they mean the keys are strings and if so, it should all be accessible via res["humidity"] or whichever key they need.
it 's very hard to know the problem here ,still the quetion has some blurry it seem everything working but we are here just guesing 😔 , if the users show my result maybe we can figert it out 😅😅
you was correct , but 😔I still don't know how this is happen 😂😂
0
public getDisplayData(): Observable<Interndata[]> 

says to return an Observable of an Array of Interndata. This means that you have Typed the response as an array Interndata[] perhaps this is what you want but in that case the json must be an array like this.

[{"humidity": 49.099998474121094, "temperature": 24.899999618530273}] 

and would be accessed like this:

this.interndata[0].humidity

To help debug this you can add an error handler like this

public getDisplayData(): Observable<Interndata[]> {
       return this.http.get<Interndata[]>('http://192.168.0.110:8080/process')
        .pipe<Interndata[]>(
          catchError(err=>console.log('Err: '+err))
        );
}

This is a good tutorial on Error Handling in RxJx: https://blog.angular-university.io/rxjs-error-handling/

2 Comments

Unfortunatetly, this does not work either. I tried also to remove the array in the class and in the method. constructor(private servinterdata : InterndataService){ servinterdata.getDisplayData().subscribe(res => console.log("Result" + res.humidity), err => console.log('HTTP error',err) ); } The response is then Resultundefined
My suspician is that your service is mislabeling the response type as text. You can check this by opening the debug window in your browser Ctrl+Shift+I typically in FF and Chrome, and perusing the network tab. Refresh will be necessary. Also, I made a change to my answer (pipe need to be typed as well)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.