繁体   English   中英

Angular 8 类型“void”不可分配给类型“ObservableInput”<any> '</any>

[英]Angular 8 Type 'void' is not assignable to type 'ObservableInput<any>'

我有一个方法,我试图每 5 分钟调用一次。 它基本上检查用户的网络连接。 但是我收到以下错误,并且不确定为什么Type 'void' is not assignable to type 'ObservableInput<any>'

这是我的代码

  ngOnInit() {
    this.subscription = timer(0, 300000).pipe(
        switchMap(() => this.checkNetwork())
      ).subscribe(result => this.statusText = result);
  }


  checkNetwork() {
    this.speedTestService
    .getKbps({
      iterations: 2,
      file: {
        path:
          "https://upload.wikimedia.org/wikipedia/commons/b/b9/Pizigani_1367_Chart_1MB.jpg",
        size: 1024,
        shouldBustCache: true,
      },
      retryDelay: 60000,
    })
    .subscribe((speed) => {
      console.log("Your speed is " + speed);
      if (speed < 0.4) {
        this.errorService.openErrorPopup('Connection has dropped or is too slow.');
        this.logout();
      }
    });
  }

当我调用this.checkNetwork()时,错误出现在这里switchMap(() => this.checkNetwork()) )

有什么帮助吗?

switchMap要求 Observable 在回调中返回,但您不返回任何内容。

尝试这个。

  ngOnInit() {
    this.subscription = timer(0, 300000).pipe(
        switchMap(() => this.checkNetwork())
      ).subscribe((speed) => {
        console.log("Your speed is " + speed);
        if (speed < 0.4) {
          this.errorService.openErrorPopup('Connection has dropped or is too slow.');
          this.logout();
        }
        
        this.statusText = ....
        
      });
  }


  checkNetwork() {
     return this.speedTestService.getKbps({
              iterations: 2,
              file: {
              path:
               "https://upload.wikimedia.org/wikipedia/commons/b/b9/Pizigani_1367_Chart_1MB.jpg",
              size: 1024,
              shouldBustCache: true,
            },
            retryDelay: 60000,
            });
  }

您的代码应该是:-

 ngOnInit() {
    this.subscription = timer(0, 300000).pipe(
        switchMap(() => this.checkNetwork())
      ).subscribe(result => this.statusText = result);
  }


  checkNetwork() {
    return this.speedTestService
    .getKbps({
      iterations: 2,
      file: {
        path:
          "https://upload.wikimedia.org/wikipedia/commons/b/b9/Pizigani_1367_Chart_1MB.jpg",
        size: 1024,
        shouldBustCache: true,
      },
      retryDelay: 60000,
    })
    .pipe(map((speed) => {
      console.log("Your speed is " + speed);
      if (speed < 0.4) {
        this.errorService.openErrorPopup('Connection has dropped or is too slow.');
        this.logout();
      }
    }));
  }

由于交换机 map 需要一个 observable,并且从 checkNetwork 中您没有返回一个 Observable,您只是订阅了一个不需要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM