angular - 如何将离子数据存储与 BehaviorSubject 和 Observable 一起使用
问题描述
我正在尝试使用 Angular 9 / Ionic 5 创建应用程序
我正在使用离子数据存储
所以,我的auth.service.ts看起来像:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage'
import { BehaviorSubject, Observable, from } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class AuthService {
private currentTokenSubject: BehaviorSubject<string>
public currentToken: Observable<string>
constructor(
private http: HttpClient,
private storage: Storage,
) {
this.getToken()
.then(res => {
this.currentTokenSubject = new BehaviorSubject(res)
this.currentToken = this.currentTokenSubject.asObservable()
}
)
}
async getToken() {
return await this.storage.get('accessToken')
}
public get currentTokenValue(): string {
return this.currentTokenSubject.value;
}
login(username: string, password: string) {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic ' + btoa(username + ':' + unescape(encodeURIComponent(password)))
})
return this.http.post<Token>(`${environment.apiUrl}/auth/signin`, { }, { headers })
.pipe(map((res: Token) => {
let token = res.token
// store user details and jwt token in local storage to keep user logged in between page refreshes
this.storage.set('accessToken', token);
return token;
}));
}
logout() {
// remove user from local storage to log user out
this.storage.remove('accessToken');
this.currentTokenSubject.next(null);
}
}
jwt.interceptor.ts看起来像:
import { Injectable } from '@angular/core'
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'
import { Observable } from 'rxjs'
import { AuthService } from '@app/_services'
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private authService: AuthService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
const currentToken = this.authService.currentTokenValue;
if (currentToken) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentToken}`
}
});
}
return next.handle(request);
}
}
所以,当我尝试调用服务时,我得到了错误,因为 Ionic Storage 返回 Observable:
Error: Uncaught (in promise): TypeError: Cannot read property 'value' of undefined
TypeError: Cannot read property 'value' of undefined
at AuthService.get currentTokenValue [as currentTokenValue] (auth.service.ts:39)
问题是:从 Ionic Storage 获取价值并使用它的正确方法是什么?
解决方案
您在为其分配任何值之前尝试访问BehaviorSubject
's getter 的问题。value
最好避免使用value
getter 并订阅 observable 以保持异步。尝试以下
auth.service.ts
export class AuthService {
private currentTokenSubject = new BehaviorSubject<string>(null); // <-- assign default value here
constructor(
private http: HttpClient,
private storage: Storage,
) {
this.getToken().then(
res => {
this.currentTokenSubject.next(res); // <-- push token to the observable
}
);
}
async getToken() {
return await this.storage.get('accessToken');
}
public get currentTokenValue(): Observable < string > {
return this.currentTokenSubject.asObservable(); // <-- return observable here
}
login(username: string, password: string) {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic ' + btoa(username + ':' + unescape(encodeURIComponent(password)))
})
return this.http.post<Token>(`${environment.apiUrl}/auth/signin`, {}, { headers }).pipe(
map((res: Token) => {
let token = res.token;
// store user details and jwt token in local storage to keep user logged in between page refreshes
this.storage.set('accessToken', token);
this.currentTokenSubject.next(token); // <-- also push new token here?
return token;
}));
}
logout() {
// remove user from local storage to log user out
this.storage.remove('accessToken');
this.currentTokenSubject.next(null);
}
}
现在您需要订阅该函数currentTokenValue()
来检索令牌。
一些组件/服务
export class SomeComponent implements OnInit {
token: string;
ngOnInit() {
this.authService.currentTokenValue().subscribe(
token => {
if(token) { // <-- check if token valid because it can also be null
this.token = token;
}
}
);
}
}
推荐阅读
- python - 使用自定义 og:tags 生成自定义链接以在linkedin帖子上共享
- keras - Keras 在构建之后调用之前访问父层的 output_shape
- javascript - 如何使用 JavaScript 在屏幕上移动两辆车
- mysql - 如何将一个mysql查询的结果传递给另一个mysql查询?
- flutter - 在颤动的底部导航栏中使用提供程序调用页面
- python - python模拟给定理论概率的实际发生次数
- python - 如何让 tkinter 在继续之前等待一行代码完成?
- javascript - PDF.JS - 如何在服务器上存储 PDF
- javascript - React 仅显示 Firestore 上收集的一条数据
- git - git-diff 控制台默认颜色含义