【问题标题】:Angular nested HTTP call without using success/failure block不使用成功/失败块的角度嵌套 HTTP 调用
【发布时间】:2020-04-24 16:09:02
【问题描述】:

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

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

【问题讨论】:

    标签: angular http rxjs


    【解决方案1】:

    您可以为此使用switchMap

    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
        }
    

    【讨论】:

      【解决方案2】:

      只需使用switchMap:

      this.userService.createSampleUser({ fName: 'surendra', lName: 'tarai' })
          .pipe(switchMap(() => this.userService.getUsers('BLR')))
          .subscribe(users => ...)
      

      编辑:

      const createUser$ = this.userService.createSampleUser({ fName: 'surendra', lName: 'tarai' });
      const handlingError = catchError(err => of(err); // guarantee flow continuity
      const getUsers$ = this.userService.getUsers('BLR');
      const stream$ = createUser$.pipe(handlingError, concatMap(() => getUsers$);
      
      stream$.subscribe();
      

      请注意,stream$ 订阅将仅发出 getUsers$ 的结果,如果您想获取所有“子流”的事件,请使用concat 而不是concatMap

      【讨论】:

      • 这里如果 createSampleUser 给出任何 5** 系列错误,则不会调用 getUsers 方法。我只想在 getUsers 之前调用 createSampleUser 服务...无论 createSampleUser 服务给出错误还是成功
      • 我可以使用 subscribe => 完整块来实现。但是您编辑的代码比我的初始代码长。寻找简短而甜蜜的解决方案
      • 是的,我明白了,但关键是最后我们只需要使用我编辑的代码进行一次订阅,无论如何,我尊重你的意见。
      • 我标记你的答案是正确的,因为它按预期工作......但我建议你尽可能分享一些简短的 coed。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2017-04-07
      相关资源
      最近更新 更多