我有一个方法findFdsUserSearchParams,它调用一个服务getContactSearchParams api,但是在返回一个值之前,剩余的状态变量会执行并且(d)是未定义的,然后我看到这个值在服务中返回,但是它没有返回到这个方法,尽管我在这里有一个订阅
this.contactFdsService.getContactSearchParams(this.cdsid).subscribe((d) =>
如何使它等待getContactSearchParams获得值,然后执行下一行,即如果(d) {} so将得到一个值。
findFdsUserSearchParams(): any {
if (this.cdsid.length > 1) {
this.contactFdsService.getContactSearchParams(this.cdsid).subscribe((d) => {
if (d) {
this.fdsSearchData = d;
if (d.length > 0) {
this.showfdsSearchParam = true;
} else {
this.showfdsSearchParam = false;
}
} else {
this.fdsSearchData = d;
this.showfdsSearchParam = true;
}
});
}
}这是带有api调用的服务。
getContactSearchParams(cdsid: string): Observable<any> {
const body = JSON.stringify({ site: 'ras-admin', cdsid: cdsid, CDSIDBeginsWith: cdsid, searchType: "get-fds-user-search" });
const endpoint = environment.endpointContacts;
const endpointFds = environment.endpointContactsFds + "/find-users/execute/0";
const httpOptions = {
headers: new HttpHeaders({
"x-app-validate": environment.fdsAppValidateHeader,
"No-Auth": "True",
}),
};
return this.http.post<any>(endpoint, body).pipe(
switchMap((fdsDataFromSql) => {
if (fdsDataFromSql == null || (Array.isArray(fdsDataFromSql) && fdsDataFromSql[0].fdsContact.length == 0)) {
const bodyFirstName = JSON.stringify({ cdsid: cdsid, FirstNameContains: cdsid, searchType: "get-fds-user-search" });
this.http.post<any>(endpointFds, body, httpOptions).subscribe((d) => {
this.cdsid = d.results;
this.cdsval = this.cdsid.concat(this.firstNameval);
});
this.http.post<any>(endpointFds, bodyFirstName, httpOptions).subscribe((d) => {
this.firstNameval = d.results;
this.cdsval = this.cdsid.concat(this.firstNameval);
});
const combinedVal: Observable<any> = of(this.cdsval)
.pipe(
distinct()
);
return combinedVal;
} else {
return of(fdsDataFromSql[0].fdsContact);
}
}),
catchError((error) => {
this._isError = true;
return EMPTY;
}),
finalize(() => {
this._isLoading = false;
this._isError = false;
})
);
}
}发布于 2022-06-17 15:23:34
当您订阅可观察到的内容时,您会告诉result永远不要等待结果,并执行以下语句,因为订阅()是一个同步函数。要解决这个问题,您需要将以下语句放入订阅函数中,否则您可以使用异步函数(例如:const result = await this.http.get("/blabla").toPromise();),然后脚本将永远不会执行下一个语句,直到他得到结果。
https://stackoverflow.com/questions/72660794
复制相似问题