Angular2 订阅里面订阅 [英] Angular2 subscribe inside subscribe

查看:22
本文介绍了Angular2 订阅里面订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular2 中,根据第一个 API 调用的结果实现第二个 API 调用的正确方法是什么?我的 Angular2 组件之一具有以下方法.我尝试在另一个订阅中完成订阅,而第二个订阅的响应总是未定义".

In Angular2, what would be the correct way to implement a second API call based on the result from the first API call? One of my Angular2 components has the following method. I tried with having a subscribe inside another subscribe on complete and the response from the second subscribe is always 'undefined'.

根据 CozyAzure 的建议进行编辑.

Edit based on suggestion from CozyAzure.

export interface Result {
  host: string;
  resourceUri: string;
  groupId?: string;
  resource?: any;
}

private curateResults(searchTerm: string, searchResults: SearchResults): Result[] {
    const results: Result[] = [];
    if (searchResults.results !== undefined && searchResults.results.length > 0) {
      searchResults.results.forEach((result: any) => {
        const processedSearchResult: Result = {
          host: result.origin.toString(),
          resourceUri: result.url.toString()
        };
        processedSearchResult.resource = undefined;
        processedSearchResult.groupId = undefined;
        this.bopsHttpService.getResourceData(processedSearchResult.host, processedSearchResult.resourceUri)
          .flatMap((resource: any) => {
            processedSearchResult.groupId = this.getGroupIdFromResource(resource, 'groupId');
            if (processedSearchResult.groupId === undefined) {
              const uriParts = processedSearchResult.resourceUri.split('/');
              const predicate = uriParts[uriParts.length - 2];
              if (predicate === 'group') {
                processedSearchResult.groupId = uriParts[uriParts.length - 1];
                return Observable.empty();
              } else {
                return this.bopsHttpService.getGroupRelation(processedSearchResult.resourceUri.split('/').pop());
              }
            } else {
              return Observable.empty();
            }
          })
          .subscribe((relation: any) => {
            if (relation !== undefined) {
              processedSearchResult.groupId = relation.objectId;
              console.log('Fetched Group ID: ', processedSearchResult.groupId);
            }
          });
        results.push(processedSearchResult);
      });
    }
  return results;
}

我的http调用如下:

My http calls are as follows:

  public getGroupRelation(subjectId: string): Observable<Relation> {
    const path = `${this.bopsServiceUrl}/relation/${subjectId}/group`;
    const queryParameters = new URLSearchParams();
    queryParameters.set('at', new Date().toISOString());
    const options = new RequestOptions({
      headers: this.headers,
      search: queryParameters
    });
    return this.http.get(path, options)
      .map((response: Response) => response.json())
      .catch((error: any) => Observable.throw(error.json().error
        || 'BOPS Server error during get group relation Operation', 
          error.json()));
  }

  public getResourceData(host: string, resourceUri: string): Observable<any> {
    const path = host + resourceUri;
    const queryParameters = new URLSearchParams();
    queryParameters.set('at', new Date().toISOString());
    const options = new RequestOptions({
      headers: this.headers,
      search: queryParameters
    });
    return this.http.get(path, options)
      .map((response: Response) => response.json())
      .catch((error: any) => Observable.throw(error
        || 'BOPS Server error during Get Resource Data Operation'));
  }

推荐答案

如果你想链接你的 Observables,你将需要使用 .flatMap().flatMap().then() 相同,如果您正在考虑 Promise 方式.

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.

改为这样做:

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);
        }
    })

您可以在 flatMap() 回调中进行任何干预.您可以检查 groupId 是否存在,然后才能进行下一次调用.如果没有,只需使用 Obersvable.empty() 返回一个空的 Observable.

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().

这篇关于Angular2 订阅里面订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆