我正在尝试创建一个可观察的,在localStorage变量发生更改时返回值的方法。我的订阅服务器不会在更改localStorage时获得新值(或者就内存中的变量而言)。
navbar.component.js
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
/**
* This class represents the navigation bar component.
*/
@Component({
moduleId: module.id,
selector: 'sd-navbar',
templateUrl: 'navbar.component.html',
styleUrls: ['navbar.component.css'],
providers: [UserService]
})
export class NavbarComponent implements OnInit {
loggedIn: boolean;
constructor(private us: UserService) { }
ngOnInit() {
this.us.isLoggedIn().subscribe(loggedIn => {
this.loggedIn = loggedIn;
});
}
}auth.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UserService } from '../shared/services/user.service';
/**
* This class represents the lazy loaded AuthComponent.
*/
@Component({
moduleId: module.id,
selector: 'sd-auth',
templateUrl: 'auth.component.html',
styleUrls: ['auth.component.css'],
providers: [UserService]
})
export class AuthComponent implements OnInit {
authParams = {
provider: '',
params: {}
};
constructor(private route: ActivatedRoute, private us: UserService) { }
ngOnInit() {
this.route.params.forEach((param) => {
this.authParams.provider = param.authprovider;
});
this.route.queryParams.forEach((queryParams) => {
this.authParams.params = queryParams;
});
this.us.logIn("google", JSON.stringify(this.authParams));
console.log(JSON.parse(localStorage.getItem('authParams')));
}
}user.service.ts
// user.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
@Injectable()
export class UserService {
private loggedIn = false;
private logger = new Observable<boolean>((observer: Subscriber<boolean>) => {
observer.next(this.loggedIn);
});
constructor() {
if (localStorage.getItem('authParams')) {
this.loggedIn = !!JSON.parse(localStorage.getItem('authParams')).params.id_token;
} else {
this.loggedIn = false;
}
}
logIn(provider: string, providerResponse: string) {
localStorage.setItem('authParams', providerResponse);
this.loggedIn = true;
}
isLoggedIn(): Observable<boolean> {
return this.logger;
}
logOut() {
localStorage.removeItem('authParams');
this.loggedIn = false;
}
}流看起来就像
步骤1- Navbar订阅UserService (获取loggedIn=false的默认值)步骤2- AuthComponent更新UserService (sets = true)
我在Navbar的订阅没有更新。我在这里错过了什么。我是否需要在logIn方法中加入类似事件发射器的UserService方法?
发布于 2016-11-03 05:43:18
你想要的是一个主题。查看文档这里。
举个简单的例子,如下所示:
export class UserService {
...
private logger = new Subject<boolean>();
...
isLoggedIn(): Observable<boolean> {
return this.logger.asObservable();
}
logIn(provider: string, providerResponse: string) {
localStorage.setItem('authParams', providerResponse);
this.loggedIn = true;
this.logger.next(this.loggedIn);
}
logOut() {
localStorage.removeItem('authParams');
this.loggedIn = false;
this.logger.next(this.loggedIn);
}
...发布于 2019-11-04 09:25:01
我编写了一个StorageService来支持可观察的localStorage和sessionStorage。它在一个服务中同时支持这两种服务。
StorageService
import { BehaviorSubject, Observable } from 'rxjs';
/**
* Storage service
* used for persist application data in observable key value pair
*/
export class StorageService {
private storage: Storage;
private subjects: Map<string, BehaviorSubject<any>>;
/**
* Constructor with service injection
* @param storage
*/
constructor(storage: Storage) {
this.storage = storage;
this.subjects = new Map<string, BehaviorSubject<any>>();
}
/**
* watch data of given key
* @param key
* @param defaultValue
*/
watch(key: string): Observable<any> {
if (!this.subjects.has(key)) {
this.subjects.set(key, new BehaviorSubject<any>(null));
}
var item = this.storage.getItem(key);
if (item === "undefined") {
item = undefined;
} else {
item = JSON.parse(item);
}
this.subjects.get(key).next(item);
return this.subjects.get(key).asObservable();
}
/**
* get data of given key
* @param key
*/
get(key: string): any {
var item = this.storage.getItem(key);
if (item === "undefined") {
item = undefined;
} else {
item = JSON.parse(item);
}
return item;
}
/**
* set value on given key
* @param key
* @param value
*/
set(key: string, value: any) {
this.storage.setItem(key, JSON.stringify(value));
if (!this.subjects.has(key)) {
this.subjects.set(key, new BehaviorSubject<any>(value));
} else {
this.subjects.get(key).next(value);
}
}
/**
* remove given key
* @param key
*/
remove(key: string) {
if (this.subjects.has(key)) {
this.subjects.get(key).complete();
this.subjects.delete(key);
}
this.storage.removeItem(key);
}
/**
* clear all available keys
*/
clear() {
this.subjects.clear();
this.storage.clear();
}
}LocalStorageService
import { Injectable, Inject } from '@angular/core';
import { StorageService } from './storage.service';
/**
* Local storage service
* used for persist application data in observable key value pair
*/
@Injectable()
export class LocalStorageService extends StorageService {
/**
* Constructor with service injection
* @param window
*/
constructor(@Inject('WINDOW') private window: any) {
super(window.localStorage);
}
}SessionStorageService
import { Injectable, Inject } from '@angular/core';
import { StorageService } from './storage.service';
/**
* Session storage service
* used for persist application data in observable key value pair
*/
@Injectable()
export class SessionStorageService extends StorageService {
/**
* Constructor with service injection
* @param window
*/
constructor(@Inject('WINDOW') private window: any) {
super(window.sessionStorage);
}
}以下是您如何使用该服务:
import { LocalStorageService } from './local-storage.service';
export class TestClass implements OnInit, OnDestroy {
constructor(
private localStorage: LocalStorageService,
) { }
ngOnInit() {
// get current value
this.localStorage.get('foo');
// set new value
this.localStorage.set('foo', 'bar');
// watch value changes
this.localStorage.watch('foo').pipe(takeUntil(this.unsubscribe)).subscribe(foo => console.log('foo changed', foo));
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
}(我对TypeScript非常陌生,有几个月的经验。)欢迎任何改进或建议:-)
发布于 2017-06-22 00:54:54
更准确地说,使用来自import { BehaviorSubject } from 'rxjs/BehaviorSubject';的import { BehaviorSubject } from 'rxjs/BehaviorSubject';
前任:
@Injectable()
export class UserService {
public username = new BehaviorSubject<string>('');
public preferredLanguage = new BehaviorSubject<string>('');
public preferredTimezone = new BehaviorSubject<string>('');
constructor(
private router: Router,
private jwtTokenService: JwtTokenService
) {
let token: string = localStorage.getItem('token'); // handled for page hard refresh event
if (token != null) {
this.decode(token);
}
}
private decode(token: string) {
let jwt: any = this.jwtTokenService.decodeToken(token);
this.username.next(jwt['sub']);
this.preferredLanguage.next(jwt['preferredLanguage']);
this.preferredTimezone.next(jwt['preferredTimezone']);
}
public setToken(token: any) {
localStorage.setItem('auth_token', token);
this.decode(token);
}
}并了解BehaviorSubject与可观察性的区别:BehaviorSubject对可观察的?
https://stackoverflow.com/questions/40393703
复制相似问题