Angular 首次尝试使用时返回未定义或Null的本地存储数据

Angular 首次尝试使用时返回未定义或Null的本地存储数据,angular,ionic-framework,local-storage,ionic4,Angular,Ionic Framework,Local Storage,Ionic4,我是新使用爱奥尼亚和我尝试使用本地存储,我的问题是以下 我有一个登录表单,当登录过程成功时,它将服务器响应的一些数据存储到本地存储中,然后转到主页的下一页。 当主页启动ngOnInit时,我试图从本地存储中检索数据,并将其显示在html文件中的变量调用客户机上。 但在我第一次尝试这样做时,在html文件中变量cliente its应该是空白的空间,并使用控制台日志查看值,显示Undefined 如果我在成功登录后检查本地存储区中的数据,我需要的所有信息都会存储在那里,并且它也在那里 如果我刷新页

我是新使用爱奥尼亚和我尝试使用本地存储,我的问题是以下

我有一个登录表单,当登录过程成功时,它将服务器响应的一些数据存储到本地存储中,然后转到主页的下一页。 当主页启动ngOnInit时,我试图从本地存储中检索数据,并将其显示在html文件中的变量调用客户机上。 但在我第一次尝试这样做时,在html文件中变量cliente its应该是空白的空间,并使用控制台日志查看值,显示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);
    });
  }


}
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() {
  }


}
主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>

这可能有助于为您的问题提供最低限度的代码。此外,建议为您的最小代码问题创建stackblitz。这可能有助于为您的问题提供最小代码。另外,建议您为最小的代码问题创建stackblitz
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;
    });
  }
}