Угловой HTTP-запрос для файла JSON возвращает неопределенный - PullRequest
0 голосов
/ 08 мая 2019

Я недавно начал изучать Angular, но это намного сложнее, чем я думал. Я хочу прочитать в файле JSON в диаграмме на моей главной странице приложения. Это для чтения файла с температурой из моего PI и визуализации их на графике.

Я пробовал разные методы, которые я нашел в Интернете, чтобы получить это, но ничего не получалось. Я начал с обычного учебного пособия здесь (https://angular.io/guide/http). Тем не менее, я не понимаю, почему я всегда получаю неопределенный объект взамен и поэтому не могу прочитать любые данные из него. Сейчас я просто хочу зарегистрировать его в консоли.

Что я делаю не так?

мой-бар-chart.components.ts

import { Config } from './../config';
import { Component, OnInit } from '@angular/core';
import { TempReaderService } from '../temp-reader.service';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Observable, of, Subject } from 'rxjs';


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



export class MyBarChartComponent implements OnInit {
  constructor(private tempReader: TempReaderService, private http: HttpClient) { }
  public barChartOptions = {
    scaleShowVerticalLines: false,
    responsive: true
  };

  public labels: string[];

  public barChartType = 'bar';
  public barChartLegend = true;

  /*
  public barChartLabels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  */
  public barChartData = [
    {data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
    {data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'}
  ];
  public barChartLables;

  config: Config;

  showConfig() {
    this.tempReader.getConfig()
      // clone the data object, using its known Config shape
      .subscribe((data: Config) => this.config = { ...data });
    console.log(this.config.heroesUrl);
  }
  ngOnInit() {
    this.showConfig();
  } 
}

Темп-reader.service.ts

import { Config } from './config';
import {HttpClient } from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators'; // add map function to observable


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

  getData() {
    console.log(this.http.get('assets/temp.json'));
    var txt = this.http.get('assets/temp.json');
    console.log(txt);
    return txt;
  }

  configUrl = 'assets/config.json';

  getConfig() {
    // now returns an Observable of Config
    return this.http.get<Config>(this.configUrl);
  }


  constructor(private http: HttpClient) { }
}

export interface JSONa {
  barData: string;
  barLabel: string;
}

Ответы [ 2 ]

0 голосов
/ 08 мая 2019

Вам необходимо прочитать содержимое файла json, используя http Итак, сначала вам нужно создать сервис для получения контента json

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable';
import { Injectable } from "@angular/core";

@Injectable()
export class JsonSettingService {
  constructor(private http: HttpClient) {
  }

   public getJsonData(): Observable<any> {
    return this.http.get("./assets/jsonFile.json");
  }
}

Затем добавьте ваш сервис в ваш компонент

export class MyComponent implements OnInit {
    constructor(
        private jsonSettingService : JsonSettingService  
    ) { }

   ngOnInit(){
       this.jsonSettingService.getJsonData().subscribe(data => {
            console.log(data);
        });
   }
}

Пожалуйста, дайте мне знать, если вам нужна помощь.

0 голосов
/ 08 мая 2019

http возвращает Observable, на который вы должны подписаться, чтобы получить данные

getData() {
    this.http.get('assets/temp.json')
              .subscribe(data => return data , err => return null);
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...