【问题标题】:Angular: how to make localStorage works asyncAngular:如何使 localStorage 异步工作
【发布时间】:2019-05-27 17:14:21
【问题描述】:

我在登录时尝试通过从 localStorage 发送 ID 来获取数据。我尝试的一切都不起作用,我唯一想到的是从本地存储中获取 ID 是同步的。我希望有人可以帮助我使其异步。不幸的是,我无权在此处显示 API。代码:

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  loginUrl = 'xxxxxxxxxx';
  errorData: {};


  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = {email: email, password: password};
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
          return  restaurant;
        }
      }),
      catchError(this.handleError)
    );
  }

  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
      return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

  currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
  currID = this. currRestaurant.id;
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  submitted = false;
  returnUrl: string;
  error: {};
  loginError: string;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private authService: AuthService
    ) { }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.authService.logout();
  }

  get email() { return this.loginForm.get('email'); }
  get password() { return this.loginForm.get('password'); }

  onSubmit() {
    this.submitted = true;
    this.authService.login( this.email.value, this.password.value).subscribe((data) => {

       if (this.authService.isLoggedIn) {
            const redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/';
                this.router.navigate([redirect]);
      } else {
            this.loginError = 'email or password is incorrect.';
    }
      },
      error => this.error = error
    );

  }

}

感谢大家的宝贵时间

【问题讨论】:

  • @FatehMohamed 我试着跟随,但遇到了很多麻烦
  • 您能否澄清一下,您的实际错误是什么?您正在运行此代码,并且 this.authService.isLoggedIn 永远不会评估为 true 还是其他?由于您正在访问订阅中的 localStorage,因此异步/同步应该不是问题。也许您可以创建一个最小的工作示例作为 stackblitz。此外,不太确定这是否只是您的问题中的一个错误,但isLoggedIn 是一个函数,您不应该在订阅中调用this.authService.isLoggedIn() 吗?

标签: javascript angular local-storage


【解决方案1】:

有一些错误:

  1. 您是否知道您使用的是原生localStorage,而不是您导入的import { LocalStorage } from '@ngx-pwa/local-storage';(如果您想使用它,它也应该注入constructor,并以异步方式使用)李>
  2. if (this.authService.isLoggedIn) { 永远为真,因为this.authService.isLoggedIn 是一个函数,它不是一个假值。您可能想要执行它 - if (this.authService.isLoggedIn()) {
  3. redirectUrl 始终未定义,因为您提供的 sn-ps 未为其分配任何值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-09
    • 2018-05-29
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    相关资源
    最近更新 更多