簡體   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