我是Ionic的新手,我正在尝试使用本地存储,我的问题是以下情况...
我有一个登录表单,当登录过程成功时,它会将服务器响应的一些数据存储到本地存储中,然后转到下一个“主页”。 当主页启动ngOnInit时,我试图从本地存储中检索数据并将其显示在我的html文件的变量调用cliente上。 但是我第一次尝试这样做,在html文件中,变量cliente的空间应该为空白,然后使用控制台日志查看该值显示为Undefined。
如果成功登录后我在本地存储中检查数据,则我需要的所有信息都将存储在该存储中。
如果我刷新页面,它将显示所有内容。
我认为这与本地存储中的值尚未准备好有关,当我尝试在页面上显示它并且刷新页面时,所有这些都准备就绪了
我已经尝试了几种方法,但是没有一种起作用。 这是我的代码,如果有谁可以帮助我提出建议。 注意:如果您在我的代码中看到了一些奇怪的东西,请打扰我,目前我知道它看起来像科学怪人,但是我已经对代码进行了太多更改,以至于我不知道如何制作它工作...
Main.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from './../../services/data.service';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, ActivatedRoute } from '@angular/router';
import { AuthService } from './../../services/auth-service.service';
import { MenuController } from '@ionic/angular';
import { Storage } from '@ionic/storage';
import { GetService } from '../../get.service';
import { BarcodeScanner, BarcodeScannerOptions } from '@ionic-native/barcode-scanner/ngx';
@Component({
selector: 'app-main',
templateUrl: './main.page.html',
styleUrls: ['./main.page.scss'],
})
export class MainPage implements OnInit {
cliente: any;
points: any;
id: any;
data: any;
error: any;
parsedJson: any;
urlSearchParams: any;
scannedData: {};
constructor(private menu: MenuController, private router: Router, private dataService: DataService, private route: ActivatedRoute,
public authService: AuthService, private storage: Storage, private newsService: GetService,
private barcodeScanner: BarcodeScanner) {
this.storage.get('ID').then((val) => {
this.id = val;
const urlSearchParams = new URLSearchParams();
urlSearchParams.append('cliente', this.id);
this.newsService
.getData(`puntos?${urlSearchParams.toString()}`).subscribe(data => {
this.data = data;
if (this.data['Error'] === 200) {
this.storage.set('Puntos', this.data['SaldoPuntos']);
}
// console.log(data);
});
});
this.storage.get('Auth').then((val) => {
console.log(val);
if (val === 0 || val === null) {
console.log('Logged Out');
this.router.navigate(['login']);
return;
}
if (val !== 0) {
this.data = this.dataService.getjsonresult();
this.storage.get('Nombre').then((val) => {
this.cliente = val;
// console.log('Your Name is', val);
});
this.storage.get('Puntos').then((val) => {
this.points = parseInt(val);
// console.log('Your Name is', val);
});
// console.log(this.data);
}
});
}
ngOnInit() {
this.storage.ready().then(() => {
this.storage.get('Nombre').then((val) => {
this.cliente = val;
// console.log('Your Name is', val);
});
});
this.storage.get('Puntos').then((val) => {
this.points = parseInt(val);
// console.log('Your Name is', val);
});
}
scanCode() {
this.barcodeScanner.scan().then(barcodeData => {
alert('Barcode data ' + JSON.stringify(barcodeData));
this.scannedData = barcodeData;
}).catch(err => {
console.log('Error', err);
});
}
}
主要HTML
<ion-header>
<ion-toolbar color="dark">
<ion-buttons slot="start">
<ion-menu-button contentId="content" autoHide="false"></ion-menu-button>
</ion-buttons>
<ion-title>Home</ion-title>
<ion-buttons slot="end">
<ion-button >
<ion-icon slot="end" name="person" ></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content padding>
<div class="container-fluid">
<h1 style="text-align: center; color: white">MiCliente</h1><img src="../../../assets/icon.png"/>
</div>
<!-- <div class="topright" style="position: fixed; padding-top: 50px;"><ion-icon name="arrow-up"></ion-icon><br>Registra tu compra</div> -->
<div class="welcomeTextDiv">
<h1 class="welcomeText">BIENVENIDO</h1><br><br>
</div>
<h5 style="font-size: 25px; margin: auto; color: red !important; text-transform: uppercase; text-align: center" class="errorMessage">
{{ error }}
</h5>
<div style="margin-left: auto; margin-right: auto; width: fit-content;" *ngIf="!cliente">
<ion-spinner></ion-spinner>
</div>
<div >
<div class="userDiv">
<h2 class="userText">{{ cliente }}</h2>
</div>
<div class="messageDiv">
<h2 class="messageText">Felicidades has ganado {{ points }} puntos</h2>
</div>
</div>
<div style="text-align: center;color: white">
<h3>REGISTRA TU COMPRA</h3>
<ion-button size="large" (click)="scanCode()" color="light">
<ion-icon slot="icon-only" name="barcode"></ion-icon>
</ion-button>
</div>
</ion-content>
Login.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse, HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { forkJoin, of, Observable } from 'rxjs';
import { forEach } from '@angular/router/src/utils/collection';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, NavigationExtras } from '@angular/router';
import { GetService } from '../../get.service';
import { ToastController, MenuController } from '@ionic/angular';
import { DataService } from './../../services/data.service';
import { AuthService } from './../../services/auth-service.service';
import { Storage } from '@ionic/storage';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
public usuario:any;
public password:any;
result: any =[];
data: any;
allData: Observable<any>;
loginJson: any;
tutorialComplete: any;
constructor(public http: HttpClient, private router: Router, private GetService: GetService, public toastController: ToastController, public menuCtrl: MenuController,
private dataService: DataService, private storage: Storage, public authService: AuthService ) {
// set a key/value
this.storage.get('Auth').then((val) => {
console.log(val);
if (val === '0' || val === ' ' ){
this.storage.set('ID', 0 );
this.storage.set('Nombre', '');
this.storage.set('Puntos', '0' );
this.storage.set('Auth', '0' );
} if ( val === '1'){
console.log('Logged in');
this.router.navigateByUrl('/menu/main');
return;
}
});
}
ionViewWillEnter() {
//this.menuCtrl.enable(false);
}
Login(){
var hash = require('hash.js');
var pass = hash.sha256().update(this.password).digest('hex');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('idusuario', this.usuario);
urlSearchParams.append('password', pass);
this.GetService.getData(`LOGINPREM?${urlSearchParams.toString()}`)
.subscribe(async data => {
this.result = JSON.stringify(data); // get data in result variable
this.allData = JSON.parse(this.result); // parse json data and pass json string
this.dataService.setjsonresult(this.result);
// alert(this.dataService.getjsonresult());
this.storage.set('ID', this.allData['Cliente']);
this.storage.set('Nombre', this.allData['Nombre']);
this.storage.set('Puntos', this.allData['SaldoPuntos']);
this.storage.set('Auth', 1 );
this.authService.login();
if (this.allData['Error']== 200) {
const toast = await this.toastController.create({
message: "Bienvenido " + this.allData['Nombre'],
position: 'top',
duration: 2000
});
toast.present();
this.router.navigateByUrl('/menu');
return false;
} else {
const toast = await this.toastController.create({
message: "Codigo de Error: " + this.allData['Error'] + " Descripcion: " + this.allData['Descripcion'] ,
position: 'top',
duration: 2000
});
toast.present();
this.router.navigateByUrl('login');
return false;
}
});
}
async finish() {
await this.storage.set('tutorialComplete', true);
await this.storage.set('ID', 0 );
await this.storage.set('Nombre', '');
await this.storage.set('Puntos', '0' );
await this.storage.set('Auth', '0' );
this.tutorialComplete = this.storage.get('tutorialComplete');
this.router.navigateByUrl('/login');
}
ngAfterViewInit() {
}
ngOnInit() {
}
}
我什至试图在中间使用服务以确保数据在那里并准备好getname:
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { from } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
data: any;
jsonresult: any;
userID: any;
Points: any;
constructor( private storage: Storage, ) {
}
// Json de Resultado de todos los procesos
public setjsonresult(jsonresult: any) {
this.jsonresult = jsonresult;
}
public getjsonresult() {
return this.jsonresult;
}
public getPoints() {
this.storage.get('Puntos').then((val) => {
this.Points = parseInt(val);
});
return this.Points;
}
getName() {
this.storage.get('Nombre').then((val) => {
return val;
});
}
}