我正在处理一种情况,在网络连接期间,我们有时可能有有限的互联网连接,无法从服务器获得响应,或者作为HttpError失败响应。在此,我尝试每秒钟都要点击这个URL来检查我们是否得到了响应。
我正在尝试这个代码,这是很好的在线方法,但当我打开我的互联网的is不返回我的虚值。
fetch-data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Posts } from './posts';
import { Observable, interval, throwError, of } from 'rxjs';
import { take, exhaustMap, map, retryWhen, retry, catchError, tap, mapTo, } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class FetchDataService {
public url = 'https://jsonplaceholder.typicode.com/posts';
constructor(private _httpClient: HttpClient) { }
getData() {
const ob = interval(1000);
return ob.pipe(
exhaustMap(_ => {
return this._httpClient.get<Posts[]>(this.url, { observe: 'response' });
}),
map(val => {
if (val.status === 200)
return true;
throw val;
}),
retryWhen(errors => {
return errors.pipe(map(val => {
if (val.status === 0)
return false;
}))
})
);
}
// private handleError(error: HttpErrorResponse) {
// if (error.error instanceof ErrorEvent) {
// // A client-side or network error occurred. Handle it accordingly.
// console.error('An error occurred:', error.error.message);
// } else {
// // The backend returned an unsuccessful response code.
// // The response body may contain clues as to what went wrong,
// console.error(
// `Backend returned code ${error.status}, ` +
// `body was: ${error.error}`);
// if (error.status !== 200)
// return of(false);
// }
// // return an observable with a user-facing error message
// return throwError(
// 'Something bad happened; please try again later.');
// };
}pulldata.component.html
import { Component, OnInit } from '@angular/core';
import { FetchDataService } from '../fetch-data.service';
import { Observable } from 'rxjs';
import { Posts } from '../posts';
@Component({
selector: 'app-pulldata',
templateUrl: './pulldata.component.html',
styleUrls: ['./pulldata.component.css']
})
export class PulldataComponent implements OnInit {
public data;
public error = '';
constructor(private _fecthDataServe: FetchDataService) { }
ngOnInit() {
this._fecthDataServe.getData().subscribe(val => {
this.data = val;
console.log(this.data);
});
}
}以这种方式检查互联网连接的最佳解决方案是什么?
发布于 2019-02-18 23:02:13
我个人的偏好是,由于数据开销的原因,不使用HTTP来执行此操作。每个HTTP请求都将包含cookie数据和其他报头,它们在这类场景中通常是无用的。
您可以使用Web套接字吗?有了这些,您就可以打开到服务器的连接,与HTTP不同,它不需要关闭。它可以永远开放。您还可以订阅事件以获得有关连接丢失的通知。Web还有一个额外的好处,那就是它是一种基于TCP的新协议,而不是HTTP,因此需要发送的网络数据要少得多。
let socket = new WebSocket('wss://yourserver/socket...');
socket.addEventListener('open', () => console.log('connection has been opened'));
socket.addEventListener('close', () => console.log('connection has been closed'));在您的情况下,您还可能希望签出重新连接WebSocket,当连接下降时,它会重新连接。当然,您也可以自己编写这个小包装。
此外,什么可能是一个更简单的解决方案。您可以在online对象:阅读有关MDN的更多信息上订阅window /阅读有关MDN的更多信息事件
function updateOnlineStatus(event) {
var condition = navigator.onLine ? "online" : "offline";
// ...do something with the new status
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);这两个解决方案都应该很容易地包装在一个角度服务,但让我知道,如果这是可行的和/或如果这些解决方案是一种选择。
https://stackoverflow.com/questions/54756469
复制相似问题