Angular 保存在服务中的数据在页面刷新或更改时丢失
我有一个Angular 5应用程序,我正在尝试使用Google OAuth登录来获取用户名,然后在服务中设置该用户名作为登录用户。在我添加登录名之前,我在服务中手动设置了该值,它可以正常工作。现在,我正在通过谷歌登录设置用户名。每次页面刷新(或调用新的服务实例)时,我设置的值似乎都会丢失 该值从Google登录返回正确(我在控制台中进行了检查),因此我知道那里一切正常。我对角度服务的印象是,它们在其他模块中是恒定的?是不是每次我调用该服务时,它都在创建一个新的空“tempuser”变量?如果是这样的话,有没有办法让我在整个应用程序中保留该值,直到用户注销 这就是服务本身:Angular 保存在服务中的数据在页面刷新或更改时丢失,angular,angular-services,google-oauth,Angular,Angular Services,Google Oauth,我有一个Angular 5应用程序,我正在尝试使用Google OAuth登录来获取用户名,然后在服务中设置该用户名作为登录用户。在我添加登录名之前,我在服务中手动设置了该值,它可以正常工作。现在,我正在通过谷歌登录设置用户名。每次页面刷新(或调用新的服务实例)时,我设置的值似乎都会丢失 该值从Google登录返回正确(我在控制台中进行了检查),因此我知道那里一切正常。我对角度服务的印象是,它们在其他模块中是恒定的?是不是每次我调用该服务时,它都在创建一个新的空“tempuser”变量?如果是这
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from "@angular/http";
@Injectable()
export class WmApiService {
//private _baseUrl = "http://wm-api.webdevelopwolf.com/"; // Test server api
private _baseUrl = "http://localhost:58061/"; // Dev server api
tempuser = "";
tempuseravatar = "";
tempuserfullname = "";
tempuseremail = "";
userloggedin = 0;
modules: any;
constructor(private _http: Http) {
console.log('Wavemaker API Initialized...');
}
// On successful API call
private extractData(res: Response) {
let body = res.json();
return body || {};
}
// On Error in API Call
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
// Basic Get W/ No Body
getService(url: string): Promise<any> {
return this._http
.get(this._baseUrl + url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
// Basic Post W/ Body
postService(url: string, body: any): Promise<any> {
console.log(body);
let headers = new Headers({'Content-Type': 'application/json'});
return this._http
.post(this._baseUrl + url, body, {headers: headers})
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
}
并且临时用户值设置为:
import { Component, OnInit } from '@angular/core';
import { WmApiService } from '../wm-api.service';
import { Router } from "@angular/router";
declare const gapi: any;
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private _wmapi: WmApiService, private router: Router) { }
public auth2: any;
userProfile: any;
user: any;
// Initalise Google Sign-On
// NOTE: Currently registered to http://localhost:4200/ - will need to change when on server to final URL
public googleInit() {
gapi.load('auth2', () => {
this.auth2 = gapi.auth2.init({
client_id: '933803013928-4vvjqtql0nt7ve5upak2u5fhpa636ma0.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
scope: 'profile email',
prompt: 'select_account consent'
});
this.attachSignin(document.getElementById('googleBtn'));
});
}
// Log user in via Google OAuth 2
public attachSignin(element) {
this.auth2.attachClickHandler(element, {},
(googleUser) => {
// Get profile from Google
let profile = googleUser.getBasicProfile();
// Save user to the API until changed
this._wmapi.tempuser = profile.getName().match(/\(([^)]+)\)/)[1];
this._wmapi.tempuseravatar = profile.getImageUrl();
this._wmapi.tempuserfullname = profile.getName();
this._wmapi.tempuseremail = profile.getEmail();
// Log the user in
this._wmapi.userloggedin = 1;
// Redirect to dashboard
this.router.navigate(['/dashboard']);
}, (error) => {
alert(JSON.stringify(error, undefined, 2));
// To get auth token - googleUser.getAuthResponse().id_token;
// To get user id - profile.getId();
});
}
ngAfterViewInit(){
this.googleInit();
}
ngOnInit() {
}
}
这里有几件事情看起来不正常
- 从组件中取出gapi.load()等内容并将其放入服务中
- 尽可能在应用程序级别而不是组件(或惰性模块)级别提供服务
- 页面重新加载问题
sessionStorage
或localStorage
。如果有这样的东西需要持续进行跨页面重新加载,那么您还应该在应用程序中构建并提供一个存储服务,为WM API服务(和其他服务)提供序列化/反序列化服务。同样,WMAPI服务被注入这个存储,这样它就可以在启动时(在它的构造函数中)配置自己
Http
,Headers
,Response
,基本上整个@angular/Http
在angular 4.3中被弃用-您应该使用HttpClient
和@angular/common/Http
的朋友。改变应该非常简单,而且值得。
另外,尝试退出Http客户端上的.toPromise()
,进入可观察对象。这将使在应用程序中使用其他东西(也可以观察到)变得更容易,而且更改也相对较小-Http(客户端)在成功或失败后都可以观察到,因此您的逻辑应该仍然相同(只需使用subscribe(successHandler,errHandler)
而不是then(successHandler,errHandler)
)
我看到您也在使用
document.getElementById
(可能还有其他东西)。您最好不要直接使用浏览器全局变量,而是插入提供的代理。从长远来看,您会感谢您自己做到了这一点。是的,您可以在Angular中拥有一个服务的多个实例,但不是每次调用它。一个服务在相同级别的模块中有相同的实例。因此,要获得服务的单个实例,请在app.module.ts中提供。此外,服务中存储的任何数据在刷新时都可能丢失。您可以出于同样的目的使用localStorage
或sessionStorage
在刷新页面时,我还面临同样的数据丢失问题。您需要在app.module.ts的提供者部分添加服务详细信息。另外,使用localStorage存储数据。刷新页面时,从localStorage检索数据
注意:-将数据以加密格式存储在localStorage中。有一个javascript库crypto js,可用于加密和解密。是的,您可以在Angular中有多个服务实例,但不是每次调用它时都有。服务在同一级别的模块中具有相同的实例。因此,要获得服务的单个实例,请在app.module.ts
中提供它。此外,服务中存储的任何数据都可能在刷新时丢失。您可以出于同样的目的使用localStorage
或sessionStorage
。谢谢你,巴德-如果你想把它作为一个答案,如果你喜欢在localStorage中保存数据是不安全的,我会勾选if off。任何人都可以查看它,直到数据被加密。你知道如何将加密数据用于本地存储并在读取时解密吗?这很有用@Zlatko,谢谢。但是,如果使用浏览器的devtools(手动)删除localStorage,该怎么办?当用户重新加载页面时,localStorage将为空。在这种情况下,我们必须再次从原始源(即服务器)获取数据?或者解决方案是什么?谢谢,但不是一件小事。我的意思是,你的令牌(或者有时是cookie)是你的身份识别手段——这就是你知道它是同一个用户的方式。如果他们删除了浏览历史记录以及您的令牌
import { Component, OnInit } from '@angular/core';
import { WmApiService } from '../wm-api.service';
import { Router } from "@angular/router";
declare const gapi: any;
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private _wmapi: WmApiService, private router: Router) { }
public auth2: any;
userProfile: any;
user: any;
// Initalise Google Sign-On
// NOTE: Currently registered to http://localhost:4200/ - will need to change when on server to final URL
public googleInit() {
gapi.load('auth2', () => {
this.auth2 = gapi.auth2.init({
client_id: '933803013928-4vvjqtql0nt7ve5upak2u5fhpa636ma0.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
scope: 'profile email',
prompt: 'select_account consent'
});
this.attachSignin(document.getElementById('googleBtn'));
});
}
// Log user in via Google OAuth 2
public attachSignin(element) {
this.auth2.attachClickHandler(element, {},
(googleUser) => {
// Get profile from Google
let profile = googleUser.getBasicProfile();
// Save user to the API until changed
this._wmapi.tempuser = profile.getName().match(/\(([^)]+)\)/)[1];
this._wmapi.tempuseravatar = profile.getImageUrl();
this._wmapi.tempuserfullname = profile.getName();
this._wmapi.tempuseremail = profile.getEmail();
// Log the user in
this._wmapi.userloggedin = 1;
// Redirect to dashboard
this.router.navigate(['/dashboard']);
}, (error) => {
alert(JSON.stringify(error, undefined, 2));
// To get auth token - googleUser.getAuthResponse().id_token;
// To get user id - profile.getId();
});
}
ngAfterViewInit(){
this.googleInit();
}
ngOnInit() {
}
}