【问题标题】:TypeScript: Best way to create Data access layerTypeScript:创建数据访问层的最佳方式
【发布时间】:2021-01-30 00:36:49
【问题描述】:

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

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

component.example.ts

getUsers () {
  this.dataLayer.getUsers().subscribe (...)
}

data-access-layer.ts

getUsers () {
  if (this.connectionMode == 'online') {
     this.httpcliente.post (...)
  } else {
     this.sqliteclient.query ("...")
  }
}

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

enum AccessDataSqLite {
   getUsers = "...",
   getData = "...",
}

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

非常感谢

【问题讨论】:

标签: angular database typescript sqlite


【解决方案1】:

如果你想构建这种行为,你可以简单地实现Strategy pattern

例子:

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

堆栈闪电战: https://stackblitz.com/edit/angular-ivy-fggs4r?file=src/app/data-layer.service.ts

【讨论】:

  • 这正是我所需要的,我会用你的概念来构建解决方案,谢谢!!!!
  • 这段代码有一些问题,但最明显的是你没有管理(热)observable的订阅,这会导致内存泄漏,即使服务被销毁.
  • @enno.void 您链接的答案不正确。您在上面定义服务的方式不会自动使其成为单例。您必须在 @Injectable 装饰器中使用 providedIn: 'root'。见angular.io/guide/singleton-services
猜你喜欢
  • 2021-11-16
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2023-03-12
  • 2021-05-14
相关资源
最近更新 更多