Javascript 角度2:创建后访问Cookie
我有两个组件和一个服务 组成部分: 1:登录组件 2:标题组件(共享) 服务: 1:authentication.service 在LoginComponent中,我使用authentication.service进行身份验证,成功身份验证后,我将用户信息添加到Cookie中,最后,我自动导航到返回URL页面,在返回页面中,我有一个用于标题的组件,该组件必须显示保存的Cookie中的用户信息,但是cookie中没有任何内容,除非我使用F5按钮手动刷新页面 我的问题是如何在不刷新页面的情况下访问cookie 更新 这是我想要得到cookie的地方:Javascript 角度2:创建后访问Cookie,javascript,angular,typescript,cookies,Javascript,Angular,Typescript,Cookies,我有两个组件和一个服务 组成部分: 1:登录组件 2:标题组件(共享) 服务: 1:authentication.service 在LoginComponent中,我使用authentication.service进行身份验证,成功身份验证后,我将用户信息添加到Cookie中,最后,我自动导航到返回URL页面,在返回页面中,我有一个用于标题的组件,该组件必须显示保存的Cookie中的用户信息,但是cookie中没有任何内容,除非我使用F5按钮手动刷新页面 我的问题是如何在不刷新页面的情况下访问c
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以提供可观察变量:
认证服务:
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);
}
}
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'));
}
}
}
我建议使用
可观察的来实现这一点。因此,登录后将通知您的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$.subscribe(user => console.log(user.username))
这种行为在不同的浏览器中常见吗?如果在浏览器控制台中运行document.cookie
,您会得到什么?通过document.cookie,我可以得到cookie,cookie存在,但在我的Header组件中,直到我刷新页面才加载cookie。我更新我的问题以获得更详细的信息,这很奇怪。如果在您的headerComponentngonit
中调用console.log(document.cookie)
您什么也得不到?headerComponent选择器放置在AppComponent中,以在整个应用程序中显示此代码返回错误:无法读取未定义的属性您的注释太一般,我无法帮助您,详细说明或更新您的代码。因此:1。你不需要严格限制用户,2。为什么要使用this.user$.asObservable()
而不是简单地这个.user$
?3.您将在控制台.log(this.currentUser)中明确获得'
因为它可能在subscribe方法完成之前被调用。如果你愿意的话,我将与你聊天30分钟,加入我,我们将修复它Hanks,crash你的解决方案是解决我的问题的关键,但我用不同的场景来实现它,我使用了这篇文章并这样实现:好的,很高兴你找到了一篇文章,为你指明了正确的方向,并最终解决了你的问题;)
user$.subscribe(user => console.log(user.username))