不使用成功/失败块的角度嵌套HTTP调用

在这里,createSampleUser服务可以从服务器给出成功/错误响应。但我想在createSampleUser服务调用之后调用getUsers服务。 因为我接下来不在这里使用错误块,所以我为什么要编写这2/3行代码。 有什么方法可以在不检查第一个服务调用的成功/错误响应的情况下调用嵌套调用?

getUsers() {
        this.userService.createSampleUser({ fName: 'surendra', lName: 'tarai' })
            .subscribe(
                next => { },
                error => { },
                () => {
                    this.users$ = this.userService.getUsers('BLR');
                }
            );
    }
评论
  • jquia
    jquia 回复

    Simply use switchMap:

    this.userService.createSampleUser
      .pipe(switchMap(() => this.userService.getUsers('BLR')))
      .subscribe(users => ...)
    
  • onam
    onam 回复

    You can use switchMap for this.

    import { switchMap } from 'rxjs/operators';
    ....
    getUsers() {
            this.userService.createSampleUser({ fName: 'surendra', lName: 'tarai' })
                .pipe(switchMap(sampleUser => this.userService.getUsers('BLR')))
                // .subscribe(); You have to subscribe to this stream. If this is a service,
                // I would subscribe from the component. If it's a component, 
               //then keep the subscribe and do something with it
        }