简体   繁体   English

Angular HttpClient订阅…没有返回数据?

[英]Angular HttpClient Subscription … no data returned?

I want to call some data from database in angular via HttpClient Methods. 我想通过HttpClient方法从角度调用数据库中的某些数据。 Then I am formatting the data for some charts. 然后,我将格式化某些图表的数据。 The 2 Methods are "getData" to get the data, and the other method is a dataFormatter() to format the data. 这两个方法是用于获取数据的“ getData”,另一个方法是用于格式化数据的dataFormatter()。 I can call the data, it logs into the browser console, howerver, I cannot process that data further in my other method... why? 我可以调用数据,它会登录到浏览器控制台,但是,我无法用其他方法进一步处理该数据……为什么?

Somehow, I think it is a subscription problem or so, because the data is not passed along into my second method it seems. 不知何故,我认为这是一个订阅问题,因为数据似乎没有传递到我的第二种方法中。

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: the return value to my variable this.dataArray is somehow of type "Subscriber"... and it seems its closed.. how can I get he right data format or subscribe again to it so that I can process the data further? 编辑:我的变量this.dataArray的返回值某种程度上是“ Subscriber”类型的。。。它似乎已关闭..如何获取正确的数据格式或再次订阅该数据格式,以便可以进一步处理数据?

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
closed
:
true

You need to subscribe the observable and once the data is received, only then format the data by passing it to the second function. 您需要预订可观察对象,并且一旦接收到数据,就只能通过将其传递给第二个函数来格式化数据。

this.getData(this.suff_url).subscribe(Response => {          
    console.log("response:",Response);
    // format the response here
});

If you want await to work, you may convert the subscription to promise using toPromise 如果您想await工作,可以使用toPromise将订阅转换为toPromise

await this.getData(this.suff_url).toPromise()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM