我正在使用
ngx-cookie-service
包来存储与我的应用程序相关的一些数据。
我需要在基础路径'/'
上保存此cookie,这样每次就可以确切地知道如何检索它。
我的此 cookie 需要更新,当发生这种情况时,新的cookie必须存储在相同的路径(即'/'
)中。问题是有时候在我刷新页面时,会在新的路径下保存一个新的cookie,因此当尝试使用this.cookieService.get(cookieName, '/')
检索它时,显然会失败。虽然我明确指定使用path为'/'
,但并不总是发生这种情况,这使得调试变得更加困难。
这是我使用cookie的服务
const urlParamsCookieName = 'errepiuapp-url-params';
/**
* This service keeps track of the keys used to retrieve objects from the backend.
*/
@Injectable({
providedIn: 'root'
})
export class KeyLookupService {
private _lookupUrlSegments = ['students', 'macro', 'lto', 'sto', 'reports'];
private _paramsMap$: BehaviorSubject<Map<string, any>>;
private get paramsMap() {
return this._paramsMap$.getValue()
}
constructor(
private cookieService: CookieService,
private router: Router
) {
if (!this.router.url.includes('auth') && !this.cookieService.check(urlParamsCookieName)) {
this.router.navigate(['/auth']);
}
this._paramsMap$ = new BehaviorSubject<Map<string, any>>(
new Map<string, any>(
this.cookieService.check(urlParamsCookieName) ?
this.getParamsFromCookie().map((value, i) => [this._lookupUrlSegments[i], value]) :
this._lookupUrlSegments.map(segment => [segment, null])
)
);
this._paramsMap$.subscribe(_ => {
this.updateCookie(); //*********** PROBLEM HERE ***********
});
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(event => {
this.updateCookie(); //*********** PROBLEM HERE ***********
})
).subscribe();
this.updateCookie(); //*********** PROBLEM HERE ***********
}
addParam(key: string, value: any) {
this._paramsMap$.next(this.paramsMap.set(key, value));
}
public getParams(...lookupKeyword: string[]): Map<string, any> {
if (lookupKeyword) {
return new Map<string, any>([...this.paramsMap.keys()]
.filter(key => lookupKeyword.includes(key))
.map(key => [key, this.paramsMap.get(key)]));
}
return this.paramsMap;
}
private getParamsFromCookie(): any[] {
return Array.from(this.cookieService.get(urlParamsCookieName).split(','));
}
private updateCookie() {
if (this.cookieService.check(urlParamsCookieName)) {
this.cookieService.delete(urlParamsCookieName, '/');
}
this.setCookie();
}
private setCookie() {
this.cookieService.set(urlParamsCookieName, [...this.paramsMap.values()].toLocaleString(), undefined, '/');
}
}