繁星點點滴滴
2022-09-29 16:03:55
我的服務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()
1 回答

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
調用返回一個 ,但這不是該方法返回的內容。訂閱是一個異步過程。啟動該進程,并且僅在 http 調用返回時才做出反應,但該方法繼續(xù)執(zhí)行并返回未定義。.subscribeObservableSearchsubscribeSearch
下面的代碼將直接從 http 調用返回 并解決您的問題。Observable
import { tap } from 'rxjs/operators';
public Search(): Observable<SearchResult[]> {
if (this.SearchResults.length === 0) {
return this.http
.get<SearchResult[]>(
environment.endpointURL + "/FooBar/Search",
this.headers
).pipe(tap(x => this.SearchResults = x));
} else {
return of(this.SearchResults);
}
}
添加回答
舉報
0/150
提交
取消