Angular/Typescript句柄在获取值后从订阅中得到结果



我希望这个问题没有答案,我找不到任何对我的案例有帮助的东西。我对angular和typescript有点陌生,所以:在调用rest调用时,如何提取订阅返回的值?代码如下:

static utilAccountName(....., queryService: QueryService) {
...
let value = true;
let name;
do {
....
// the name is built and should be changed here until there shouldn't be in the backend
value = this.theValueExists(name: string, queryService: QueryService);
} while (value);
return name;
}
private static theValueExists(name: string, queryService: QueryService): boolean {
let val;
queryService.findValueByName(name)
.subscribe(
(res) => {
val= res!= null;
}, () => {
val= false;
}
);
return val;
}
//the function from the queryService looks like this
findValueByName(name: string): Observable<MyObject> {
return this.httpClient
.get<MyObject>('/rest/byName/' + name)
.map(result => {
if (<any>result) {
return new MyObject().deserialize(result);
}
})
}

我遇到的问题是,theValueExistsval返回了undefined,我需要它在对后端的调用完成后返回值truefalse,结果在中。有办法做到这一点吗?

findValueByName异步操作。使用inttheValueExits,在执行子脚本块之前执行return val;

queryService.findValueByName(name)
.subscribe(
(res) => {
val= res!= null;
}, () => {
val= false;
}
);

最好的方法是在其他方法的基础上定义更多的可观测值。theValueExists将成为

private theValueExists(name: string, queryService: QueryService): Observable<boolean> {
return queryService.findValueByName(name).pipe(
map(res => res != null),
catchError(err => of(false)),
);

并且utilAccountName还需要用各自的rxjs实用程序来处理这些可观测值。

最新更新