我的服务
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()
总是返回上述错误吗?
答案 0 :(得分:1)
.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);
}
}