我尝试每 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();
}
});
}
错误出现在此处 switchMap(() => this.checkNetwork())
,当我调用 this.checkNetwork()
有什么帮助吗?
答案 0 :(得分:1)
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,
});
}
答案 1 :(得分:1)
你的代码应该是:-
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();
}
}));
}
因为 switch map 需要一个 observable,而从 checkNetwork 中你没有返回一个 Observable,你只是订阅了一个不需要的。