ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' even when returning an observable

ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' even when returning an observable

我发现了几个标题相同的问题,据我所知,其中一些建议解决方案基本上是 return 一个 Observable 而不是数组(其他是关于 FireBase 的,它不是以我为例)。好吧,就我而言,下面的代码执行 return 一个 Observable(查看 "getServerSentEvent(): Observable {return Observable.create ...")

我的最终目标是从 Rest WebFlux returned 流中获取所有事件。我没有越过后端,因为我很确定这个问题与 Angular.

中的某个错误有关

最重要的是,我可以调试并查看从 app.component.ts(见下图)正确进入 extratos$ 的事件。

整条日志

core.js:6185 ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
    at invalidPipeArgumentError (common.js:5743)
    at AsyncPipe._selectStrategy (common.js:5920)
    at AsyncPipe._subscribe (common.js:5901)
    at AsyncPipe.transform (common.js:5879)
    at Module.ɵɵpipeBind1 (core.js:36653)
    at AppComponent_Template (app.component.html:8)
    at executeTemplate (core.js:11949)
    at refreshView (core.js:11796)
    at refreshComponent (core.js:13229)
    at refreshChildComponents (core.js:11527)

app.component.ts

import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';
import { SseService } from './sse.service';
import { Extrato } from './extrato';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [SseService],
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  //extratos: any;
  extratos$ : Observable<any>;

  constructor(private appService: AppService, private sseService: SseService) { }

  ngOnInit() {
    this.getExtratoStream();
  }

  getExtratoStream(): void {
    this.sseService
      .getServerSentEvent("http://localhost:8080/extrato")
      .subscribe(
        data => {
          this.extratos$ = data;
        }
      );
  }
}

sse.service.ts

import { Injectable, NgZone } from '@angular/core';
import { Observable } from 'rxjs';
import { Extrato } from './extrato';

@Injectable({
  providedIn: "root"
})
export class SseService {
  extratos: Extrato[] = [];
  constructor(private _zone: NgZone) { }

  //getServerSentEvent(url: string): Observable<Array<Extrato>> {
  getServerSentEvent(url: string): Observable<any> {
    return Observable.create(observer => {
      const eventSource = this.getEventSource(url);
      eventSource.onmessage = event => {
        this._zone.run(() => {
          let json = JSON.parse(event.data);
          this.extratos.push(new Extrato(json['id'], json['descricao'], json['valor']));
          observer.next(this.extratos);
        });
      };
      eventSource.onerror = (error) => {
        if (eventSource.readyState === 0) {
          console.log('The stream has been closed by the server.');
          eventSource.close();
          observer.complete();
        } else {
          observer.error('EventSource error: ' + error);
        }
      }

    });
  }
  private getEventSource(url: string): EventSource {
    return new EventSource(url);
  }
}

app.component.html

<h1>Extrato Stream</h1>
<div *ngFor="let ext of extratos$ | async">
  <div>{{ext.descricao}}</div>
</div>

可观察到的 extratos$ 已填充的证据

当你写这个 observer.next(this.extratos); 时,这意味着 this.extratos 是你在回调的 data 参数中在组件端得到的,所以当你这样做时 this.extratos$ = data; 你实际上存储的是 extratos Array。 TypeScript 不会抱怨它,可能是因为它不够聪明,无法像您那样从头开始构建 Observable 时推断类型。

试试这个:

this.extratos$ = this.sseService
      .getServerSentEvent("http://localhost:8080/extrato");

并在模板中:<div *ngFor="let ext of extratos$ | async">