【问题标题】:Angular HttpClient Subscription ... no data returned?Angular HttpClient Subscription ...没有返回数据?
【发布时间】:2018-07-06 20:51:51
【问题描述】:

我想通过 HttpClient 方法从数据库中调用一些数据。 然后我正在格式化一些图表的数据。 这两个方法是“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);
    };
  }
}

编辑:我的变量 this.dataArray 的返回值在某种程度上属于“订阅者”类型......而且它似乎已关闭......我怎样才能获得正确的数据格式或再次订阅它,以便我可以处理进一步的数据?

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

【问题讨论】:

  • this.dataArray 在您的代码中是订阅,而不是您的请求结果。
  • 您的结果位于 subscribe 块内。用那里的数据做你需要做的事情。
  • 好的,但我不能对来自该 http 方法函数之外的返回值做任何事情吗?那么我必须在订阅块内对我的数据进行所有处理......总是?
  • 是的,欢迎来到异步世界! :)
  • 您可以在订阅之前处理您的数据,查看 rxjs 和 rxjs 操作符的文档

标签: angular publish-subscribe angular-httpclient


【解决方案1】:

您需要订阅 observable,一旦接收到数据,然后通过将数据传递给第二个函数来格式化数据。

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

如果您希望await 工作,您可以使用toPromise 将订阅转换为承诺

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    相关资源
    最近更新 更多