订阅中的Angular2订阅

Ram*_*ama 8 angular2-services angular

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

根据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;
}
Run Code Online (Sandbox Code Playgroud)

我的http调用如下:

  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'));
  }
Run Code Online (Sandbox Code Playgroud)

Coz*_*ure 8

.flatMap()如果你想链接你需要使用Observables.flatMap()就像.then()你在想Promise办法一样.

改为:

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);
        }
    })
Run Code Online (Sandbox Code Playgroud)

编辑:

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