服务中保存的数据在页面刷新或更改时丢失
Data saved in service lost on page refresh or change
我有一个 Angular 5 应用程序,我正在尝试使用 Google OAuth 登录来获取用户名,然后在服务中设置该用户名以用作登录用户。在我添加登录名之前,我在服务中手动设置了值并且它没有问题。现在我从 Google 登录名设置用户名,每次页面刷新时(或调用服务的新实例时)我设置的值似乎都会丢失。
Google 登录中的值 returns 正确(我在控制台中检查过),所以我知道那里一切正常。我对 Angular 服务的印象是它们在其他模块中保持不变?是不是每次我调用该服务时它都会创建一个新的空 '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';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
userSignedToJourney: boolean;
constructor(private _wmapi: WmApiService) { }
ngOnInit() {
this.userRegisteredToJourney();
}
// Check if Trailblazer is already on Journey
userRegisteredToJourney() {
this._wmapi
.getService("Journey/TrailblazerRegistered/" + this._wmapi.tempuser)
.then((result) => {
if (result == 1) this.userSignedToJourney = true; else this.userSignedToJourney = false;
})
.catch(error => console.log(error));
}
}
临时用户值设置如下:
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() {
}
}
这里有些地方看起来不正常。
- 依赖注入错误
您正在将 WM API 服务注入组件,然后在那里进行配置。这不应该是这种情况,您应该在服务本身和 init 上执行此操作。在获得此 google API 数据之前,服务不应处于 "ready" 状态。其一,您的组件不应该关心配置服务——它只是请求服务并使用它们。其次,如果您在其他地方使用服务,例如当没有登录组件时,谁来配置您的服务?第三,如果你有多个服务实例,那可能意味着你做错了——你应该在全局应用程序级别提供服务,以便它们都使用同一个实例,但即使没有,你仍然需要服务负责其依赖项,而不是服务消费者。
补救此特定部分的步骤:
- 从组件中取出gapi.load()等东西,放到服务中
尽可能在应用程序级别提供服务,而不是在组件(或惰性模块)级别提供服务。
- 页面重新加载问题
可能其中一些东西是持久的 - 你说在页面重新加载时,你丢失了东西。这是合乎逻辑的——在每次重新加载页面时,内存中的内容都会消失,您将拥有一个全新的应用程序。也许您想将 JWT 令牌之类的东西存储到 sessionStorage
或 localStorage
中。如果有这样的东西需要在页面重新加载时持续存在,您还应该在您的应用程序中构建并提供存储服务,为您的 WM API 服务(和其他)提供 serialization/deserialization 服务。同样,WM Api 服务注入了这个存储,因此它可以在启动时配置自己(在它的构造函数中)。
- Http 错误
Http
、Headers
、Response
基本上整个 @angular/http
在 Angular 4.3 中已弃用 - 你应该使用 HttpClient
和来自 @angular/common/http
的朋友。更改应该非常简单并且值得。
另外,尝试让自己脱离 Http 客户端上的 .toPromise()
并进入 observables。它将使整个应用程序更容易处理其他事物(也可观察到),并且变化也相对最小 - Http(客户端)可观察量在成功或失败后无论如何都会完成,所以你的逻辑应该仍然是相同的(只需使用 subscribe(successHandler, errHandler)
而不是 then(successHandler, errHandler)
).
- 文档
我看到您也在使用 document.getElementById
(可能还有其他东西)。你最好不要直接使用浏览器全局变量,而是注入 Angular 提供的代理。在漫长的 运行 中,你会感谢自己做到了这一点。
是的,您可以在 Angular 中有多个 service
实例,但不是每次都调用它。一项服务在 相同级别 模块中具有 相同 实例。因此,要拥有服务的单个实例,请在 app.module.ts 中提供它。此外,存储在服务中的任何数据都可能在 refresh.You 上丢失,可以使用 localStorage
或 sessionStorage
达到相同目的。
我也遇到过刷新页面时数据丢失的问题。您需要在 app.module.ts 的提供商部分下添加服务详细信息。另外,使用 localStorage 来存储数据。刷新页面时,从 localStorage.
检索数据
注意:- 将数据以加密格式存储在 localStorage 中。有一个javascript库crypto-js可以用来加解密
我有一个 Angular 5 应用程序,我正在尝试使用 Google OAuth 登录来获取用户名,然后在服务中设置该用户名以用作登录用户。在我添加登录名之前,我在服务中手动设置了值并且它没有问题。现在我从 Google 登录名设置用户名,每次页面刷新时(或调用服务的新实例时)我设置的值似乎都会丢失。
Google 登录中的值 returns 正确(我在控制台中检查过),所以我知道那里一切正常。我对 Angular 服务的印象是它们在其他模块中保持不变?是不是每次我调用该服务时它都会创建一个新的空 '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';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
userSignedToJourney: boolean;
constructor(private _wmapi: WmApiService) { }
ngOnInit() {
this.userRegisteredToJourney();
}
// Check if Trailblazer is already on Journey
userRegisteredToJourney() {
this._wmapi
.getService("Journey/TrailblazerRegistered/" + this._wmapi.tempuser)
.then((result) => {
if (result == 1) this.userSignedToJourney = true; else this.userSignedToJourney = false;
})
.catch(error => console.log(error));
}
}
临时用户值设置如下:
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() {
}
}
这里有些地方看起来不正常。
- 依赖注入错误
您正在将 WM API 服务注入组件,然后在那里进行配置。这不应该是这种情况,您应该在服务本身和 init 上执行此操作。在获得此 google API 数据之前,服务不应处于 "ready" 状态。其一,您的组件不应该关心配置服务——它只是请求服务并使用它们。其次,如果您在其他地方使用服务,例如当没有登录组件时,谁来配置您的服务?第三,如果你有多个服务实例,那可能意味着你做错了——你应该在全局应用程序级别提供服务,以便它们都使用同一个实例,但即使没有,你仍然需要服务负责其依赖项,而不是服务消费者。
补救此特定部分的步骤:
- 从组件中取出gapi.load()等东西,放到服务中
尽可能在应用程序级别提供服务,而不是在组件(或惰性模块)级别提供服务。
- 页面重新加载问题
可能其中一些东西是持久的 - 你说在页面重新加载时,你丢失了东西。这是合乎逻辑的——在每次重新加载页面时,内存中的内容都会消失,您将拥有一个全新的应用程序。也许您想将 JWT 令牌之类的东西存储到 sessionStorage
或 localStorage
中。如果有这样的东西需要在页面重新加载时持续存在,您还应该在您的应用程序中构建并提供存储服务,为您的 WM API 服务(和其他)提供 serialization/deserialization 服务。同样,WM Api 服务注入了这个存储,因此它可以在启动时配置自己(在它的构造函数中)。
- Http 错误
Http
、Headers
、Response
基本上整个 @angular/http
在 Angular 4.3 中已弃用 - 你应该使用 HttpClient
和来自 @angular/common/http
的朋友。更改应该非常简单并且值得。
另外,尝试让自己脱离 Http 客户端上的 .toPromise()
并进入 observables。它将使整个应用程序更容易处理其他事物(也可观察到),并且变化也相对最小 - Http(客户端)可观察量在成功或失败后无论如何都会完成,所以你的逻辑应该仍然是相同的(只需使用 subscribe(successHandler, errHandler)
而不是 then(successHandler, errHandler)
).
- 文档
我看到您也在使用 document.getElementById
(可能还有其他东西)。你最好不要直接使用浏览器全局变量,而是注入 Angular 提供的代理。在漫长的 运行 中,你会感谢自己做到了这一点。
是的,您可以在 Angular 中有多个 service
实例,但不是每次都调用它。一项服务在 相同级别 模块中具有 相同 实例。因此,要拥有服务的单个实例,请在 app.module.ts 中提供它。此外,存储在服务中的任何数据都可能在 refresh.You 上丢失,可以使用 localStorage
或 sessionStorage
达到相同目的。
我也遇到过刷新页面时数据丢失的问题。您需要在 app.module.ts 的提供商部分下添加服务详细信息。另外,使用 localStorage 来存储数据。刷新页面时,从 localStorage.
检索数据注意:- 将数据以加密格式存储在 localStorage 中。有一个javascript库crypto-js可以用来加解密