我的服务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 调用返回时才做出反应,但该方法继续执行并返回未定义。.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
提交
取消