TypeScript:创建数据访问层的最佳方法

Her*_*roa 4 database sqlite typescript angular

下午好,我正在使用 Angular 在 ionic 中创建一个应用程序,目前它处理两种连接模式:如果用户可以访问互联网则连接,如果用户没有互联网访问则断开连接

目前我有一个功能,如果用户处于连接模式,他必须调用 API,否则他必须调用 SQLite 中的查询:

组件.example.ts

getUsers () {
  this.dataLayer.getUsers().subscribe (...)
}
Run Code Online (Sandbox Code Playgroud)

数据访问层.ts

getUsers () {
  if (this.connectionMode == 'online') {
     this.httpcliente.post (...)
  } else {
     this.sqliteclient.query ("...")
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是实施此策略的最佳方法是什么,因为制定条件来验证连接是否是其中一种对我来说似乎不是最好的方法,或者可能使用枚举

enum AccessDataSqLite {
   getUsers = "...",
   getData = "...",
}
Run Code Online (Sandbox Code Playgroud)

如果您能给我发送参考资料、链接或实施该策略的更好方法,我将不胜感激

非常感谢

enn*_*oid 6

如果你想构建这种行为,你可以简单地实现策略模式

例子:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Stackblitz: https://stackblitz.com/edit/angular-ivy-fggs4r ?file=src/app/data-layer.service.ts