首页 > 解决方案 > 使用 api 登录后,我的应用程序未将数据保存在本地存储中

问题描述

在我的应用程序中,我使用返回令牌和用户名的 api 登录。我想将两者都保存在本地存储中。用户名,我想稍后在应用程序中显示。

它登录,但不保存数据。

我正在使用带角度的 Ionic 4。

app.component.ts

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.authenticationService.authenticationState.subscribe(state => {
        if (state) {
          this.authService.storage.get('nameLogued').then((val) => {
            this.nameOfUser = val;
          })
          this.router.navigate(['members', 'home']);
        } else {
          this.router.navigate(['login']);
        }
      });
    });
  }

app.component.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      <ion-icon name="contact"></ion-icon>
        {{nameOfUser}}
    </ion-title>
  </ion-toolbar>
</ion-header>

身份验证.service.ts

login(user) {
    return this.http.post(this.global.urlAPI + 'api/login', user);
 }

login.page.ts

login(form) {
    this.authService.login(form).subscribe(data => {
      this.storage.set(this.global.token_key, data['token']);
      this.storage.set('nameLogued', data['user'].name);
      this.authService.authenticationState.next(true);
      this.login_form = this.formBuilder.group({
        email: new FormControl(''),
        password: new FormControl('')
      })
    }, (error => {
      this.toast.showToastError('There is wrong data.');
    }));
  }

谢谢!

标签: angularionic-framework

解决方案


存储数据

const credentialsKey = 'currentUser'; 
login(loginData: Login): Observable<any> {
    return this.http.post<any>('Usermaster/Authenticate', loginData).pipe(
      tap(
        function (data) {
          const storage = loginData.remember ? localStorage : sessionStorage;
          storage.setItem(credentialsKey, JSON.stringify(data));
          return data;
        }
      )
    );
  }

从存储值中获取数据

 private getUser() {
    const savedCredentials = sessionStorage.getItem(credentialsKey) || localStorage.getItem(credentialsKey);
    return JSON.parse(savedCredentials);
  }

推荐阅读