我正在尝试制作一个介绍页面,该页面将读取QR码,保存代码并传递到另一个页面。这只会在您第一次打开应用程序时发生。关闭应用程序并重新打开时,不应显示简介页面。那么,我的问题是什么?我正在保存我阅读的代码,但是当我关闭应用程序并再次打开时,我保存的代码丢失了,并且出现了简介页面。我该如何解决这个问题?
我的介绍页面代码是:
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')
);
};
我app.component.ts
代码是:
import { NativeStorage } from "@ionic-native/native-storage";
const STORAGE_KEY = 'hospitals';
...
rootPage:any;
constructor(platform: Platform, statusBar: StatusBar,
splashScreen: SplashScreen, public push: Push,
public alertCtrl: AlertController,
private nativeStorage: NativeStorage) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
this.pushsetup();
this.setRootPage();
});
}
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)
);
alert(localStorage);
switch (localStorage){
case "123":
this.rootPage = LoginPage;
break;
default:
this.rootPage = IntroPage;
break;
}
}
它不会丢失。您正在检查 promise then 函数之外的值,以便它可以在获取数据之前执行。 您需要在要查找数据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)
)
}