我正在开发 Angular 服务,其中使用BehaviorSubject 来管理 IdentityToken。 BehaviorSubject 被实例化为
BehaviorSubject<IdentityToken | null>
。然后我通过调用 .asObservable()
从BehaviorSubject 派生一个新的可观察值。然而,当我将鼠标悬停在派生的可观察量上时,Typescript 会将其推断为 BehaviorSubject<IdentityToken>
。好像省略了null
。根据我的理解,派生的可观察量应该与BehaviorSubject相同。
相关代码:
private identityToken = new BehaviorSubject<IdentityToken | null>(
null
);
public identityToken$ = this.identityToken.asObservable(); // hovering the `identityToken$` typescript infers is as `BehaviorSubject<IdentityToken>`
完整代码:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { StorageKeys } from '../_models/localStorageKeys';
import { map } from 'rxjs/operators';
interface IdentityToken {
Role: string;
Permissions: string[];
}
@Injectable({
providedIn: 'root',
})
export class UserService {
private identityToken = new BehaviorSubject<IdentityToken | null>(
null
);
public identityToken$ = this.identityToken.asObservable(); // hovering the `identityToken$` typescript infers is as `BehaviorSubject<IdentityToken>`
public isAuthenticated$ = this.identityToken$.pipe(
map((token) => !!token)
);
constructor() {
this.identityToken = new BehaviorSubject<IdentityToken | null>(
this.getStoredToken()
);
}
private getStoredToken(): IdentityToken | null {
const stored = localStorage.getItem(StorageKeys.IDENTITY_TOKEN);
if (!stored) return null;
try {
return JSON.parse(stored);
} catch (e) {
localStorage.removeItem(StorageKeys.IDENTITY_TOKEN);
return null;
}
}
}
这是由于
strictNullChecks
在您的 false
中为 tsconfig
(或未设置)。