Angular2 subscribe inside subscribe

ε祈祈猫儿з 提交于 2019-12-05 03:36:53

You will need to use .flatMap() if you want to chain your Observables. flatMap() is the same as .then() if you are thinking of the Promise way.

Do this instead:

this.bopsHttpService.getResourceData(processedSearchResult.host, processedSearchResult.resourceUri)
    .flatMap(() => {
        //check if groupId exist, or whatever your logic is
        if(hasGroupId){
            //groupId exist, proceed to call your second request
            return this.bopsHttpService.getGroupRelation(processedSearchResult.resourceUri.split('/').pop());
        }
        //groupId doesn't exist, return an empty Observable.
        return Observable.empty();

    })
    .subscribe((relation) => {
        if (relation !== undefined) {
            processedSearchResult.groupId = relation.objectId;
            console.log('Fetched Group ID: ', processedSearchResult.groupId);
        }
    })

Edit:

You can do any interventions inside your flatMap() callbacks. You can check if the groupId exist or not, only then you proceed to your next call. If it doesn't, simply returns an empty Observable using Obersvable.empty().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!