javascript - Angular:如何使 localStorage 异步工作
问题描述
我在登录时尝试通过从 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;
}
登录组件.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
);
}
}
感谢大家的时间
解决方案
有一些错误:
- 您是否知道您使用
localStorage
的是 Native ,而不是您导入的那个 - (如果您想使用它,import { LocalStorage } from '@ngx-pwa/local-storage';
也应该注入它,并以异步方式使用)constructor
if (this.authService.isLoggedIn) {
将永远为真,因为它this.authService.isLoggedIn
是一个函数,它不是一个假值。您可能想要执行它 -if (this.authService.isLoggedIn()) {
redirectUrl
始终未定义,因为您提供的代码段未为其分配任何值。
推荐阅读
- udhcpc - 在 dhcp 发现期间从 dhclient 发送供应商特定信息(代码)
- javascript - 在 JavaScript 中复制元素内容
- oracle - 差距和孤岛问题 - 对数据的连续运行进行分组以获得最大和最小日期
- cron - 全天的每一分钟,但当月的第 2 天和第 7 天时,仅需要在上午 12:00-08:59 和晚上 11:00-11:59 触发
- reactjs - 如何在现有的 TypeScript 项目中使用 JS React 组件?
- machine-learning - 无法建立 arxiv 论文中提到的深度学习模型
- c - 地址运算符和汇编中的指针之间有区别吗?
- google-chrome - chrome 如何将 XHR 调用映射到 TCP 套接字
- android - GoogleSignIn 重复登录弹出窗口并且不会转到 Android API 30 的 onActivityResult
- swift - SwiftUI 按钮操作关闭中的 Swift 错误:“不能在不可变值上使用变异成员:'self' 是不可变的”