Javascript 未定义可观测返回的角度订阅
我的服务Javascript 未定义可观测返回的角度订阅,javascript,angular,Javascript,Angular,我的服务 import { Injectable } from "@angular/core"; import { Observable, of } from "rxjs"; import { SearchResult } from "../Components/container-search/Models/SearchResult"; import { environment } from "../../environments/environment"; import { HttpClie
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);
}
}
}
有人能解释一下为什么这个代码this.searchService.Search总是返回上面的错误吗?这个.subscribe调用返回的是一个可观察的,但这不是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);
}
}
你已经订阅了service@pc_coder,我想从订阅中返回可观察的内容就可以了。我应该怎么做呢?这是一个异步调用,所以您可以将子脚本从服务带到组件。然后它就可以工作了。也可以在组件中控制长度。在服务中,只需发送请求并返回response@pc_coder,我想在服务中缓存该数据,然后检查缓存的数据是否存在。如果它不进行HTTP调用,如果它确实存在,我想返回缓存的值。我应该怎么做?尽可能避免订阅服务。如果需要保存响应,则可以使用管道函数和诸如tap或map之类的运算符,并将响应分配给服务内的变量。http.get.pipetapx=>{…};这段代码确实有效,但它不会在服务中缓存搜索结果。我的最终目的是将结果缓存在服务中,然后返回缓存的结果,但是您的else条件将在这里失败。你不能得到其他条件的subscribe@pc_coder我不知道你的意思。of创建了一个可观察对象,因此可以订阅。啊,很抱歉没有注意到。@peinearydevelopment非常感谢您的帮助!
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);
}
}