如何使用Ionic 3永久保存数据?

时间:2018-05-28 11:59:09

标签: ionic-framework ionic3 ionic-native cordova-nativestorage

我试图制作一个能够读取QR码的介绍页面,保存代码并传递到另一个页面。这仅在您第一次打开应用程序时发生。关闭应用程序并重新打开时,不应显示简介页面。那么,我的问题是什么?我保存了我读过的代码,但是当我关闭应用程序并再次打开时,我保存的代码丢失了,并显示了介绍页面。我该如何解决这个问题?

我的IntroPage代码是:

127.0.0.1:8080

我的class NewActivity extends AppCompatActivity implements View.OnClickListener { EditText editEmail, editPassword, editName; Button btnSignIn, btnRegister; private ProgressDialog pDialog; String URL= "https://xyz/restapi/registration"; JSONParser jsonParser=new JSONParser(); int i=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnRegister=(Button)findViewById(R.id.btnRegister); btnRegister.setOnClickListener(this); /*btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AttemptLogin attemptLogin= new AttemptLogin(); attemptLogin.execute(editName.getText().toString(),editPassword.getText().toString(),""); } });*/ /*btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AttemptLogin().execute(); } });*/ } @Override public void onClick(View v) { new AttemptLogin().execute(); } private class AttemptLogin extends AsyncTask<String, String, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(NewActivity.this); pDialog.setMessage("Attempting for registering..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected JSONObject doInBackground(String... args) { ArrayList params = new ArrayList(); params.add(new BasicNameValuePair("cust_firstname", "Sai")); params.add(new BasicNameValuePair("cust_lastname", "Kumar")); params.add(new BasicNameValuePair("cust_phoneno", "9989219692")); params.add(new BasicNameValuePair("cust_confirmpass", "Sai@123")); params.add(new BasicNameValuePair("cust_pass", "Sai@123")); params.add(new BasicNameValuePair("cust_username", "sai@gmail.com")); JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params); return json; } protected void onPostExecute(JSONObject result) { // dismiss the dialog once product deleted //Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show(); try { if (result != null) { Toast.makeText(getApplicationContext(),result.getString("message"),Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } } 代码是:

import { NativeStorage } from '@ionic-native/native-storage';
const STORAGE_KEY = 'hospitals';
...
scannedCode:string = null;

constructor(private navCtrl: NavController, 
            private barcodeScanner: BarcodeScanner, 
            private nativeStorage: NativeStorage,
            private toast: Toast) {}

public scanCode() {
  this.barcodeScanner.scan().then(barcodeData => {
    this.scannedCode = barcodeData.text;
    if (this.scannedCode === "123"){
      this.save(this.scannedCode);
      this.navCtrl.push(LoginPage);
    }
    else{
      this.makeToastMessage('Invalid Hospital!', '5000', 'bottom');
    }
  }, (err) => {
    console.log('Error: ', err);
  });
};

private save(val){
  console.log('data added ' + val);
  this.nativeStorage.setItem(STORAGE_KEY, {property: val})
    .then(
      () => console.log('Stored item!'),
      error => this.makeToastMessage('Error storing item', '5000', 'center')
    );
};

1 个答案:

答案 0 :(得分:1)

它不会丢失。您正在检查承诺之外的值然后运行,以便在获取数据之前执行它。 您需要使用then内的切换案例来查找数据或链接承诺。

private setRootPage(){
  let localStorage:string = "Not got";
  this.nativeStorage.getItem(STORAGE_KEY)
    .then(
        item => localStorage = item.properity,
        error => console.log("Error getting item. Error: " + error)
    ).then(_=>{
         switch (localStorage){
            case "123":
                this.rootPage = LoginPage;
                break;
            default:
                this.rootPage = IntroPage;
                break;
        }
    });
}

这将确保您只有在从存储中提取值后才会检查值

或简而言之:

 private setRootPage(){
      this.nativeStorage.getItem(STORAGE_KEY)
        .then(
            item => {
                switch (item.property){
                case "123":
                    this.rootPage = LoginPage;
                    break;
                default:
                    this.rootPage = IntroPage;
                    break;
                }

            },
            error => console.log("Error getting item. Error: " + error)
        )


}