简体   繁体   English

离子2如何设置和获取本地存储的值

[英]ionic 2 how to set and get value local storage

I have 2 screens. 我有2个屏幕。 Each screen have one input field. 每个屏幕都有一个输入字段。 At last screen I need to get the entered values of all input screen at last screen. 在最后一个屏幕上,我需要在最后一个屏幕上获取所有输入屏幕的输入值。 For that I need to store the each screen value locally when I press next button. 为此,当我按下一个按钮时,我需要在本地存储每个屏幕值。 But in ionic 2 how can I do that? 但是在离子2中我该怎么做?

here my html code 这是我的HTML代码

<ion-input [(ngModel)]="SignUpData.username" name="username" type="text"  #username="ngModel" required>
</ion-input>

in my app/app.module.js : 在我的app / app.module.js中

I have this line 我有这条线

import { IonicStorageModule } from '@ionic/storage';
IonicStorageModule.forRoot()

And in my page/signup.ts 在我的页面/ signup.ts中

SignUpData = { username:''};
nextbtn() {
console.log(this.SignUpData.username);  // i am getting correct value
}

But how can I code more or import some storage to store my value (set value), And in another screen, secondscreen.ts , how can I get that locally stored value. 但是我如何编码更多或导入一些storage来存储我的值(设置值),而在另一个屏幕, secondscreen.ts ,我如何获得本地存储的值。

Fist you need to import it in the app.module.ts file: 你需要在app.module.ts文件中导入它:

import { IonicStorageModule } from '@ionic/storage';

// ...    

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    // ...
  ],
  providers: []
})
export class AppModule {}

And then inject it into any of your components or pages: 然后将其注入任何组件或页面:

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

export class MyApp {
  constructor(private storage: Storage) {

     // set a key/value
     this.storage.set('name', 'Max');

     // Or to get a key/value pair
     storage.get('age').then((val) => {
       console.log('Your age is', val);
     });
  }
}

So in the nextbtn method you'd need to save it 所以在nextbtn方法中你需要保存它

nextbtn() {
  console.log(this.SignUpData.username);
  this.storage.set('username', this.SignUpData.username);
}

And in the next page, you can get that value again like this 在下一页中,您可以像这样再次获得该值

readUsername() {
  // Notice that the get method returns a promise!
  storage.get('username').then((username) => {
    console.log(username);
  });
}

You can find more information in the Storage docs . 您可以在存储文档中找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM