Я хочу вызвать некоторые данные из базы данных в угловом режиме через методы HttpClient.
Затем я форматирую данные для некоторых графиков.
2 метода - это «getData» для получения данных, а другой метод - это dataFormatter () для форматирования данных.
Я могу вызвать данные, они входят в консоль браузера, но я не могу обрабатывать эти данные другим способом ... почему?
Почему-то я думаю, что это проблема с подпиской или около того, потому что данные не передаются во второй метод, как мне кажется.
import { Component, OnInit,NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { catchError, map, tap } from 'rxjs/operators';
import { Http,Response} from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { GeneralhttpserviceService } from '../services/generalhttpservice.service';
import { ChartdataformatterService } from '../services/chartdataformatter.service';
@Component({
selector: 'anlagenstatus',
templateUrl: './anlagenstatus.component.html',
styleUrls: ['./anlagenstatus.component.scss']
})
export class AnlagenstatusComponent implements OnInit {
private base_url = 'localhost:5555/DNZ/';
private suff_url = 'Status/betrieb/Status';
dataArray: any;
chartArray: any[];
formattedData: any;
showXAxis = true;
view = [1500,600];
timeline = true;
showYAxis = true;
gradient = false;
showLegend = true;
showXAxisLabel = false;
xAxisLabel: string = "Zeitwerte";
showYAxisLabel = false;
yAxisLabel: string = "Betriebswerte";
autoScale = true;
tooltipDisabled = false;
colorScheme = {
domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
};
constructor( private http: HttpClient, private genHttp: GeneralhttpserviceService, private chartFormatter: ChartdataformatterService) { }
ngOnInit() {
this.formattedData= this.anlagenstatusDataFormatter();
}
//all HttpClient return an RxJS Observable of something
//HttpClient.get returns the body of the response as an untyped JSON object by default.
//To catch errors, you "pipe" the observable result from http.get() through an RxJS catchError() operator.
getData(suffurl: string, id? :number): Observable<any[]> {
return this.http.get<any[]>('http://localhost:5555/DNZ/'+ this.suff_url)
.pipe(
map(data => data),
tap(data => console.log("Anlagenstatus Daten:", data)),
catchError(this.handleError('getData',[]))
)
}
/*.pipe(subscribe(Response => { console.log(Response)})
tap(data => console.log("Anlagenstatus Daten:", data)),
catchError(this.handleError('getData',[]))
)*/
anlagenstatusDataFormatter():any {
this.dataArray = this.getData(this.suff_url).subscribe(Response => { console.log("response:",Response)});
console.log("Pre-Formatted data:", this.dataArray);
for (var elem of this.dataArray) {
var entrydict ={
name: elem["_id.Demonstrator"],
series: [{
name: elem["_id.betriebsbereit"],
value: elem["Anzahl"]
}]
}
this.chartArray.push(entrydict);
}
console.log("Formatted Anlagenstatusdaten:",this.chartArray);
return this.chartArray;
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
console.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
edit: значение, возвращаемое моей переменной this.dataArray, имеет тип "Subscriber" ... и кажется, что оно закрыто ... как я могу получить правильный формат данных или снова подписаться на него, чтобы я мог обработать данные дальше?
Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
closed
:
true