TypeScript: Best way to create Data access layer
If you want to build this behavior, you can simply implement the Strategy pattern
Example:
import { Injectable } from "@angular/core";import { fromEvent, merge } from "rxjs";import { startWith, map } from "rxjs/operators";interface Strategy { getData1(): any; anotherMethod(): any;}class SQLStrategy implements Strategy { getData1() { console.log("SQl", "getData1"); } anotherMethod() { console.log("SQl", "anotherMethod"); }}class HTTPStrategy implements Strategy { getData1() { console.log("HTTP", "getData1"); } anotherMethod() { console.log("HTTP", "anotherMethod"); }}@Injectable()export class DataLayerService { private strategy; constructor() { // init strats const sqlStrategy = new SQLStrategy(); const httpStrategy = new HTTPStrategy(); merge(fromEvent(window, "online"), fromEvent(window, "offline")) .pipe( startWith(1), map(x => navigator.onLine) ) .subscribe(x => { console.log("navigator.onLine", x); this.strategy = x ? httpStrategy : sqlStrategy; }); } public getData1() { this.strategy.getData1(); } public anotherMethod() { this.strategy.anotherMethod(); }}
Stackblitz:https://stackblitz.com/edit/angular-ivy-fggs4r?file=src/app/data-layer.service.ts