代码之家  ›  专栏  ›  技术社区  ›  Jim C

错误:InvalidPipeArgument:“[object object]”用于管道“AsyncPipe”,即使在返回可观察对象时也是如此

  •  0
  • Jim C  · 技术社区  · 4 年前

    我发现了几个标题相同的问题,据我所知,其中一些问题表明解决方案基本上是返回一个可观察的而不是一个数组(其他问题是关于FireBase的,这不是我的情况)。好的,就我而言,下面的代码确实返回了一个Observable(查看“getServerSentEvent():Observable{return Observable.create…”)

    除此之外,我还可以调试并查看从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$的证据

    enter image description here

    0 回复  |  直到 4 年前
        1
  •  1
  •   Guerric P    4 年前

    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">

    推荐文章