【发布时间】: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) => this.config = { ...data }; console.log(this.config.heroesUrl););
标签: javascript node.js json angular