javascript - Angular:如何使 localStorage 异步工作

标签 javascript angular local-storage

我尝试在登录时通过从 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
    );

  }

}

感谢大家的宝贵时间

最佳答案

有一些错误:

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

关于javascript - Angular:如何使 localStorage 异步工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56322200/

相关文章:

JavaScript 性能 : Fixed Table Header & Column on Scroll

javascript - Angular4中三种类型的数据绑定(bind)指令 : [val] , [(val)] , (val) 有什么区别

javascript - 指向外部 URL 的 Angular 2 链接被视为路由的相对路径

javascript - 使用本地存储和 React 保持用户在刷新时登录

java - QR 码图像未从我的 Android 应用程序中的位图中保存

javascript - 如何在 JSX 中重复一个元素?

javascript - CKEditor 在服务器上返回错误的图像路径

javascript - 检测追加后div的长度

angular - 如何设置垫子自动完成的默认值

javascript - Angular 2 验证状态