【问题标题】:Angular http request for json file returns undefined对 json 文件的 Angular http 请求返回未定义
【发布时间】:2019-09-26 09:14:42
【问题描述】:

我最近开始学习 Angular,但它比我想象的要难。我想将一个 json 文件读入我的主应用程序页面上的图表中。这是为了从我的 PI 中读取带有温度的文件并在图表上可视化它们。

我尝试了我在网上找到的不同方法来获取它,但没有任何效果。我从这里的普通教程开始(https://angular.io/guide/http)。我仍然不明白为什么我总是得到一个未定义的对象作为回报,所以我无法从中读取任何数据。现在我只想将它登录到控制台。

我做错了什么?

我的条形图.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();
  } 
}

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

【问题讨论】:

  • 在订阅下做这个console.log(this.config.heroesUrl);
  • 我已经有了它(showConfig),或者你是什么意思?
  • .subscribe((data: Config) =&gt; this.config = { ...data }; console.log(this.config.heroesUrl););

标签: javascript node.js json angular


【解决方案1】:

http 返回一个Observable,您应该订阅以获取数据

getData() {
    this.http.get('assets/temp.json')
              .subscribe(data => return data , err => return null);
  }

【讨论】:

    【解决方案2】:

    需要使用http读取json文件内容 所以首先你需要创建一个服务来获取 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);
            });
       }
    }
    

    如果您需要任何帮助,请告诉我。

    【讨论】:

    • 这很有效,谢谢!还有一个问题,当我获取数据时它们的格式是什么,或者我如何从中获取特定值?
    • 对于搜索相同内容的人。 console.log(data[0]['data']);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多