我最近开始学习Angular,但是比我想的要难得多。我想将json文件读入我的主应用页面上的图表中。这是为了从PI中读取带有温度的文件,并在图表上将其可视化。
我尝试了在网上找到的其他方法来实现此目的,但是没有任何效果。我从这里的普通教程(https://angular.io/guide/http)开始。仍然我不明白为什么我总是得到一个未定义的对象作为回报,所以我不能从中读取任何数据。现在,我只想将其登录到控制台。
我该怎么办?
my-bar-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();
}
}
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;
}
答案 0 :(得分:0)
http
返回一个Observable
,您应该订阅以获取数据
getData() {
this.http.get('assets/temp.json')
.subscribe(data => return data , err => return null);
}
答案 1 :(得分:0)
您需要使用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);
});
}
}
如果您需要任何帮助,请告诉我。