Angular: как заставить localStorage работать асинхронно - PullRequest
1 голос
/ 27 мая 2019

Я пытаюсь получить данные при входе в систему, отправив идентификатор из localStorage.Все, что я пробовал, не работало, и единственное, что приходит мне в голову, это то, что получение идентификатора из локального хранилища работает синхронно.Я надеюсь, что кто-то может помочь мне сделать это асинхронным.К сожалению, у меня нет разрешения показывать здесь 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 Ответ

1 голос
/ 27 мая 2019

Есть некоторые ошибки:

  1. Знаете ли вы, что вы используете Native localStorage, а не тот, который вы импортируете - import { LocalStorage } from '@ngx-pwa/local-storage'; (а также он должен быть введен в constructor, есливы хотите использовать его и использовать асинхронно)
  2. if (this.authService.isLoggedIn) { всегда будет истинным, потому что this.authService.isLoggedIn является функцией и не является ложным значением.Возможно, вы захотите его выполнить - if (this.authService.isLoggedIn()) {
  3. redirectUrl всегда не определено, поскольку предоставленные вами фрагменты не присваивают ему никакого значения.
...