可观察返回值上未定义的角度订阅

我的服务


import { Injectable } from "@angular/core";

import { Observable, of } from "rxjs";

import { SearchResult } from "../Components/container-search/Models/SearchResult";

import { environment } from "../../environments/environment";

import { HttpClient, HttpHeaders } from "@angular/common/http";


@Injectable({

  providedIn: "root",

})

export class ContainerService {

  constructor(public http: HttpClient) {}


  private SearchResults: SearchResult[] = [];

  public headers = {

    headers: new HttpHeaders({

      "Content-Type": "application/json",

    }),

  };


  public Search(): Observable<SearchResult[]> {

    if (this.SearchResults.length === 0) {

       this.http

        .get<SearchResult[]>(

          environment.endpointURL + "/FooBar/Search",

          this.headers

        )

        .subscribe((x) => {

          this.SearchResults = x;

          return of(this.SearchResults);

        });

    } else {

      return of(this.SearchResults);

    }

  }

}

当我在我的组件中调用 Search() 时,它返回


TypeError: Cannot read property 'subscribe' of undefined


我的通话代码是


  ngOnInit(): void {

    this.dataSource.paginator = this.paginator;

     this.searchService.Search().subscribe((x) => {

      this.dataSource = new MatTableDataSource<SearchResult>(x);

    });

  }

有人可以解释为什么此代码总是返回上述错误吗?this.searchService.Search()


繁星点点滴滴
浏览 84回答 1
1回答

蝴蝶刀刀

调用返回一个 ,但这不是该方法返回的内容。订阅是一个异步过程。启动该进程,并且仅在 http 调用返回时才做出反应,但该方法继续执行并返回未定义。.subscribeObservableSearchsubscribeSearch下面的代码将直接从 http 调用返回 并解决您的问题。Observableimport { tap } from 'rxjs/operators';public Search(): Observable<SearchResult[]> {&nbsp; &nbsp; if (this.SearchResults.length === 0) {&nbsp; &nbsp; &nbsp; &nbsp;return this.http&nbsp; &nbsp; &nbsp; &nbsp; .get<SearchResult[]>(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; environment.endpointURL + "/FooBar/Search",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.headers&nbsp; &nbsp; &nbsp; &nbsp; ).pipe(tap(x => this.SearchResults = x));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; return of(this.SearchResults);&nbsp; &nbsp; }&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript