如果用户离线,如何从 http 请求 return 预定义值? (Angular)

How is it possible to return a predefined value from a http request, if the user is offline? (Angular)

我想缓存一些从服务器请求的数据。我这样修改了http请求:

// user.ts
export class User {
    id: number;
    name: string;
}

// inside the component:

getUsers() : Observable<User[]> {
    return this.http.get<User[]>(this.api+'/get-users').pipe(
        tap(users => {
            localStorage.setItem("cache_users", JSON.stringify(users));
        })
    );
}

如果由于服务器无法访问而导致请求失败,如何从缓存中加载用户?

你可以使用catchError

catchError(() => of(localStorage.getItem("cache_users")));

getUsers() : Observable<User[]> {
    return this.http.get<User[]>(this.api+'/get-users').pipe(
        tap(users => {
            localStorage.setItem("cache_users", JSON.stringify(users));
        }),
        catchError(() => of(localStorage.getItem("cache_users")))
    );
}

如果错误是由于客户端离线状态引起的,您可以在发出请求和 return 缓存后捕获抛出的错误:

import {of, throwError } from 'rxjs';
import {catchError} from 'rxjs/operators';
import {HttpErrorResponse} from '@angular/common/http';

getUsers() : Observable<User[]> {
    const url = `${this.api}/get-users`;
    return this.http.get<User[]>(url ).pipe(
        tap(users => localStorage.setItem(url , JSON.stringify(users))),
        catchError(error => {
          if(error instanceof HttpErrorResponse 
             && error.status=== 0
             && !error.url){
             // See 
             // Try to read the local storage. If the key is not present, return an empty list
             const rawJson = localStorage.getItem(url);
             return of(!!rawJson ? JSON.parse(rawJson) : []);
          }
          // 
          return throwError(error);
        })
    );
}

您可能想尝试不同的方法,例如使用 window.navigator.onLine 属性.