在我的Angular2应用程序中,我正在引导我希望在我的组件中共享的身份验证服务LocalStorage
:
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
LocalStorage
]);
LocalStorage
定义如下:
import {JwtHelper} from 'angular2-jwt/angular2-jwt';
import { Injectable } from 'angular2/core';
@Injectable()
export class LocalStorage {
key:string = 'jwt';
jwtHelper:JwtHelper = new JwtHelper();
username:string;
constructor() {
let token = localStorage.getItem(this.key);
if (token == null) return;
if (this.jwtHelper.isTokenExpired(token)) {
localStorage.removeItem(this.key);
} else {
this.username = this.jwtHelper.decodeToken(token).username;
}
}
login(jwt:string) {
localStorage.setItem(this.key, jwt);
}
logout() {
localStorage.removeItem(this.key);
}
isLoggedIn():boolean {
return this.username != null;
}
getUsername():string {
return this.username;
}
getToken():string {
return localStorage.getItem(this.key);
}
}
但问题是,当我在组件之间共享和更新它时,只有更新它的组件才能识别更改。它被注入组件并进行如下编辑:
constructor(private router:Router, private localStorage:LocalStorage) {
...
}
logout(event) {
event.preventDefault();
this.localStorage.logout();
this.router.navigateByUrl(RoutingPaths.home.path);
}
为什么看起来跨组件创建了这个服务的多个实例?感谢。
编辑组件模板绑定的示例是:
组件:
import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {RoutingPaths} from './routing-paths';
import {LoggedInOutlet} from './logged-in-outlet';
import {LocalStorage} from './local-storage'
@Component({
selector: 'my-app',
templateUrl: 'app/app.template.html',
directives: [LoggedInOutlet, ROUTER_DIRECTIVES]
})
export class AppComponent {
registerName:string;
constructor(private router:Router, private localStorage:LocalStorage) {
this.registerName = RoutingPaths.register.name;
}
logout(event) {
event.preventDefault();
this.localStorage.logout();
this.router.navigateByUrl(RoutingPaths.home.path);
}
}
模板:
<a *ngIf="!localStorage.isLoggedIn()" [routerLink]="[registerName]">Register</a>
最终修改
这是令人尴尬的,在实际编辑服务中的用户名后,它现在有效:
login(jwt:string) {
localStorage.setItem(this.key, jwt);
this.username = this.jwtHelper.decodeToken(jwt).username; // here
}
logout() {
localStorage.removeItem(this.key);
this.username = null; // here
}
很抱歉浪费每个人的时间。再次感谢。
答案 0 :(得分:1)
这是因为您在代码中的某处将LocalStorage指定为提供者。
检查您的任何组件是否包含:
@Component({
providers: [LocalStorage]
})
这给出了一个Injector指令,为该组件和所有子节点创建一个新实例,如果一个子节点本身没有提供的LocalStorage本身。
答案 1 :(得分:0)
但问题是,当我在组件之间共享和更新它时,只有更新它的组件才能识别更改
这是因为角度2组件模型是树:
因此,仅重新呈现更改的组件及其子组件。对于像组件包含状态的东西,您需要redux
之类的内容:https://medium.com/google-developer-experts/angular-2-introduction-to-redux-1cf18af27e6e#.yk11zfcwz
答案 2 :(得分:0)
我忘了实际修改服务中的用户名:
login(jwt:string) {
localStorage.setItem(this.key, jwt);
this.username = this.jwtHelper.decodeToken(jwt).username; // here
}
logout() {
localStorage.removeItem(this.key);
this.username = null; // here
}