程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了离子存储不适用于多个服务大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决离子存储不适用于多个服务?

开发过程中遇到离子存储不适用于多个服务的问题如何解决?下面主要结合日常开发的经验,给出你关于离子存储不适用于多个服务的解决方法建议,希望对你解决离子存储不适用于多个服务有所启发或帮助;

因此,当我在一项服务中使用 Storage 时,一切都完美无缺。现在我用一个新的 Ini-service 重构了我的代码,我也想使用 Storage 但它不起作用。它不是设置属性。所以我基本上把 app.component.ts 文件的逻辑放到了 Init-service 中,我在 app.component.ts 上的 ngOnInit() 函数中调用它。 我认为这与在 Ini-service 中使用 Storage 有关,它调用我的 Webservice,它也使用 Storage... 也许我需要使用 forWARDRef?我尝试使用它但它似乎没有帮助...(也许我用错了...)

ini.service.ts:

@Injectable({
  provIDedIn: 'root'
})
export class Iniservice {

  constructor(
    private storage: Storage,private webservice: Webserviceservice
  ) { }
...

  async someFunction() {
     console.log(await this.webservice.dostuff()); // works
     this.storage.set("foo","someValue"); // doesn't work
     console.log(await this.storage.get("foo")); // doesn't work
  }
}

webservice.service.ts:

@Injectable({
  provIDedIn: 'root'
})
export class Webserviceservice {

  constructor(
    private storage: Storage
  ) { }
...

  async dostuff() {
     return await this.storage.get("foo"); // works
  }
}

解决方法

我认为最好的做法是创建一个中央存储服务,然后将存储服务注入到其他需要与存储引擎交互的服务中。

例如,您可以创建这样的中央存储服务:

import { Injectable } from '@angular/core';

import { Storage } from '@ionic/storage-angular';

@Injectable({
  providedIn: 'root'
})
export class Storageservice {
  private _storage: Storage | null = null;

  constructor(private storage: StoragE) {
    this.initStorage();
  }

  async initStorage() {
    const storage = await this.storage.create();
    this._storage = storage;
  }

  public set(key: String,value: any) {
    this._storage?.set(key,value);
  }

  public get(key: String){
    return this._storage.get(key)
  }
}

然后,在您的 webservice 中

@Injectable({
  providedIn: 'root'
})
export class Webserviceservice {

  constructor(
    private storageservice: Storageservice
  ) { }
...

  async dostuff() {
     await this.storageservice.set("foo","somevalue");
     return await this.storageservice.get("foo"); 
  }
}

大佬总结

以上是大佬教程为你收集整理的离子存储不适用于多个服务全部内容,希望文章能够帮你解决离子存储不适用于多个服务所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。