HttpClient和Rxjs

问题描述 投票:0回答:1

我正在研究一种情况,在网络连接期间,我们有时可能会有一个有限的互联网连接,我们无法从服务器获得响应或响应失败,因为HttpError。我在此尝试每秒ping一次URL以检查我们是否得到了响应,为此

我正在尝试这个代码,这在网上方法工作正常,但当我转向我的互联网是不会返回我的虚假价值。

取-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);
    });

  }

}

以这种方式检查互联网连接的最佳解决方案是什么?

javascript angular rxjs rxjs5
1个回答
2
投票

我个人的偏好是不会因为数据开销而使用HTTP。每个HTTP请求都将包含cookie数据和其他在这些场景中通常无用的标头。

你有可能使用Web Sockets吗?通过这些,您可以打开与服务器的连接,与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'));

在您的情况下,您可能还想查看the Reconnecting WebSocket,它会在连接断开时重新连接。当然,您也可以自己编写这个小包装器。

此外,甚至可能是一个更简单的解决方案。你可以在online对象上订阅offline / window事件:read more on MDN

function updateOnlineStatus(event) {
    var condition = navigator.onLine ? "online" : "offline";

    // ...do something with the new status
}

window.addEventListener('online',  updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);

这两种解决方案都应该可以在Angular服务中轻松包装,但是如果能够解决这个问题并且/或者这些解决方案是否适合您,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.