【问题标题】:How to throw error after subscription timeout?订阅超时后如何抛出错误?
【发布时间】:2021-02-25 00:52:54
【问题描述】:

我只是想在 30 秒后显示在视图中(例如,当用户的连接速度太慢并且结果不会来自订阅时)。 我肯定错过了一些东西,因为即使结果全部到达,控制台超时错误消息仍然出现。 这是我尝试过的:

searchInfo() {
    this.isLoading = true;
    this.info= [];
    const source = this.infoService.searchInfo('help');
    source.pipe(
        timeout(30000),
        takeUntil(this.onDestroy$)
    ).subscribe((infoTable: infoTableContent) => {
        this.info.push(infoTable);
        this.isLoading = false;
    }),
        (err) => {
            this.isLoading = false;
            console.log(err, 'Sorry, ...')  //not working
        }

我希望在尝试订阅 30 秒后显示“抱歉,检索数据时间过长”之类的消息。 先谢谢大家了

【问题讨论】:

    标签: rxjs angular11


    【解决方案1】:

    您在subscribe 中的next 回调之后有一个额外的)
    因此,您的 error 回调将被忽略。

    .subscribe((infoTable: infoTableContent) => {
      this.info.push(infoTable);
      this.isLoading = false;
    }), // <-- This paranthesis closes the subscribe method
    

    以下按预期工作

    .subscribe(
      (infoTable: infoTableContent) => {
        this.info.push(infoTable);
        this.isLoading = false;
      },
      (err) => {
        this.isLoading = false;
        console.log(err, 'Sorry, ...');
      }
    );
    

    【讨论】:

      【解决方案2】:

      当我使用 Mocked Services 运行它时,它对我来说运行得很好:

      const mockService = {
        searchInfo: msg => NEVER.pipe(startWith({key: msg}))
      };
      const onDestroy$ = timer(5000);
      let isLoading = true;
      const info = [];
      mockService.searchInfo('help').pipe(
        timeout(1000),
        takeUntil(onDestroy$)
      ).subscribe({
        next: (mockTable: any) => {
          info.push(mockTable);
          isLoading = false;
        },
        error: err => {
          isLoading = false;
          console.log('Sorry, ...', err);
        }
      });
      

      我怀疑您的错误可能是由于格式错误(括号放在错误的位置等)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-18
        • 2021-11-23
        • 2018-07-05
        • 1970-01-01
        相关资源
        最近更新 更多