首页 > 解决方案 > 如何在 ionic 5 中使用本机存储

问题描述

我希望你没事,我需要一些帮助。所以在这里,在我的应用程序中,我创建了一个功能,当您按下按钮时,允许您将主题从浅色更改为深色。它工作得很好,但是当您重新启动应用程序时,主题会自动恢复亮起。你知道我如何用 ionic 的原生存储来录制(我猜是字符串主题)吗?

import { Component } from '@angular/core';
import { NativeStorage } from '@ionic-native/native-storage/ngx'
import { EmailComposer } from '@ionic-native/email-composer/ngx';



@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
theme:string = "light";

  constructor(public nativeStorage:NativeStorage, private emailComposer: EmailComposer) {}

  switchTheme(){
    if(this.theme=='light'){
      document.body.classList.add("dark");
      this.theme="dark";
      console.log(this.theme)
    } else {
      document.body.classList.remove("dark");
      this.theme='light';
      console.log(this.theme)
    }
  }

  sendEmail() {
    let email = {
      to:'my-mail',
      subject: 'My Feedback',
      isHtml: true 
    };

    this.emailComposer.open(email);
  }

}

非常感谢你。

标签: typescriptionic-frameworkstoragenativeionic5

解决方案


你已经注入了 NativeStorage - 只需使用它。

来自官方文档:

this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Stored item!'),
    error => console.error('Error storing item', error)
  );

this.nativeStorage.getItem('myitem')
  .then(
    data => console.log(data),
    error => console.error(error)
  );

见这里: https ://ionicframework.com/docs/native/native-storage

希望这可以帮助。


推荐阅读