获取值后,订阅的角度/打字稿处理结果

时间:2020-10-05 10:56:38

标签: 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);
                }
            })
    }

我遇到的问题是来自val的{​​{1}}返回了theValueExists,我需要它返回值undefinedtrue在调用完后端并输入结果之后。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

PHP 7.3.22-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Sep 9 2020 06:46:12) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.3.22, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.3.22-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies 异步操作。如果使用findValueByName,您需要先执行theValueExits,再执行订阅块。

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)), ); 还需要使用各自的rxjs utils处理那些可观察对象。