【发布时间】:2017-03-16 13:51:33
【问题描述】:
我正在尝试创建一个在 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;
}
}
流程看起来像
Step 1- Navbar 订阅 UserService(获取默认值 loggedIn=false) 第 2 步 - AuthComponent 更新 UserService(设置 loggedIn = true)
我在导航栏中的订阅没有更新。我在这里想念什么。我是否需要在 UserService 的 logIn 方法中添加一些东西,比如事件发射器?
【问题讨论】:
-
这里是否使用localstorage都没有关系。订阅者如何知道新价值是可用的?
logIn不会将新值推送到可观察值。此处适合使用主题或事件发射器。
标签: angular local-storage rxjs