[英]Angular subscription on observable returns undefined
我的服務
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()
總是會返回上述錯誤嗎?
.subscribe
調用返回一個Observable
,但這不是Search
方法返回的內容。 訂閱是一個異步過程。 subscribe
啟動該過程,並且僅在 http 調用返回時做出反應,但Search
方法繼續執行並返回未定義。
下面的代碼將直接從 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.