我有两个组件和一个服务
组件:
1:LoginComponent
2:HeaderComponent(共享)
服务:
1:authentication.service
在LoginComponent中我使用authentication.service进行身份验证,并在成功进行身份验证后,我将用户信息添加到Cookie中,最后,我自动导航到返回URL页面,在返回的页面中我有一个用于标题的Component必须显示保存的Cookie中的用户信息,但除非我使用F5按钮手动刷新页面,否则cookie中没有任何内容。
我的问题是如何在不刷新页面的情况下访问cookie?
更新
这是我想要获取cookie的地方:
import { Component, OnInit } from '@angular/core';
import { CookieHelper } from '../../_helpers/index';
@Component({
moduleId: module.id,
selector: 'app-header-ichart',
templateUrl: 'header.component.html',
styleUrls: ['header.component.css']
})
export class HeaderComponent implements OnInit {
currentUser = '';
isLogged = false;
constructor(private cookie: CookieHelper) { }
ngOnInit() {
this.isLogged = this.cookie.checkCookie('currentUser');
if (this.isLogged) {
this.currentUser = JSON.parse(this.cookie.getCookie('currentUser'));
}
}
}
更新2
我使用你的建议技术来实现我的目标,但需要更多的帮助:
我更新我的AuthenticationService以提供可观察变量:
的AuthenticationService:
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import { AppConfig } from '../app.config';
import { CookieHelper } from '../_helpers/index';
@Injectable()
export class AuthenticationService {
cookies: Object;
keys: Array<string>;
user$ = new Subject<any>();
constructor(private http: Http, private config: AppConfig, private cookie: CookieHelper) { }
login(username: string, password: string) {
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = `grant_type=${'password'}&username=${username}&password=${password}`;
return this.http.post(
this.config.apiUrl + '/token',
body, { headers: headers })
.map((response: Response) => {
// login successful if there's a jwt token in the response
let user = response.json();
if (user && user.access_token) {
user['username'] = username;
// Observable Variable
this.user$.next(JSON.stringify(user));
// store user details and jwt token in cookie to keep user logged in between page refreshes
this.cookie.addCookie('currentUser', JSON.stringify(user));
}
});
}
getUser(): Observable<any> {
return this.user$.asObservable();
}
logout() {
// remove user from cookie to log user out
this.cookie.removeCookie('currentUser');
// Logout Subscribe
this.user$.next(null);
}
}
HeaderComponent:
export class HeaderComponent implements OnInit {
currentUser = '';
isLogged = false;
constructor(private cookie: CookieHelper, private auth: AuthenticationService) { }
ngOnInit() {
// Get the currentUser from Observable Variable
this.auth.getUser().subscribe(currentUser => { this.currentUser = currentUser; });
console.log(this.currentUser);
this.isLogged = this.cookie.checkCookie('currentUser');
if (this.isLogged) {
this.currentUser = JSON.parse(this.cookie.getCookie('currentUser'));
}
}
}
答案 0 :(得分:1)
我建议使用Observable
来实现这一目标。因此,您的headerComponent
将在登录后收到通知。
更新您的authentication.service
,以便您拥有类似
import { Subject } from 'rxjs/Subject';
export class AuthenticationService {
user$: Subject<any>;
login() {
// login stuff
this.user$.next('userDetails');
}
logout() {
this.user$.next(null);
}
}
然后从您想要的任何组件中检查user$
可观察对象。
使用
的模板{{ (user$ | async)?.username }}
或带
的代码user$.subscribe(user => console.log(user.username))