angular - Page loosing global var values on page referesh / Browser reload
问题描述
My page works fine when invoked from a menu....Global variables loaded on ngOnInit is used to populate country list into select control and this works fine. However observed that when i reload the page thru browser refresh, global values goes empty, hence dropdown is also empty. Service fetching country list :
@Injectable()
export class Globals {
constructor(
public _countryService:CountryService, ) { }
public countryMaster = this.getscanCountries();
public getscanCountries(): Countrymaster {
this._countryService.getCountryDetails().subscribe(
data=> {this.countryDetails = data;
// console.log('superset data-->',this.countryDetails);
var res = {
countryObj: this.countryDetails.map(function(c) {
var countryName = c.Country_Name.split(",")[0]; // token before first occurence of ','
return {
continent_code: c.Continent_Code,
continent_name:c.Continent_Name,
alpha2_Country_Code: c.Two_Letter_Country_Code,
Country_Name:countryName}
} )
}
// console.log('global data 1-->',res);
this.countryMaster = res["countryObj"];
console.log('global data --Country-->',this.countryMaster );
return this.countryMaster;
}
);
return this.countryMaster;
}
}
Countries are loaded on module initialization..My component within this module access this global variable on ngOnInit.
constructor( private _reportersService :ReportersService,
private router: Router, private globals : Globals) {
this.scanCountries = this.globals.countryMaster;
} ngOnInit() {
this.browserRefresh = browserRefresh;
console.log('browserRefresh in component', this.browserRefresh )
console.log('ngOnInit', this.scanCountries)
}
Above works fine except browser refresh..
Console messages on page referesh is as follows:
Any help on this is highly appreciated.
解决方案
您应该使用 localStorage 或 sessionStorage。 https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
您还可以实现装饰器以简化您的服务。
import { Injectable } from '@angular/core';
@Injectable()
export class LocalService {
constructor(){}
set(identifier:string, value:any){
localStorage.setItem(identifier, JSON.stringify(value));
return JSON.parse(localStorage.getItem(identifier));
}
get(identifier:string){
return JSON.parse(localStorage.getItem(identifier));
}
remove(identifier:string){
localStorage.removeItem(identifier);
}
}
export function Local(identifier:string){
return function (target: any, key: string){
// property getter
let getter = function(){
return JSON.parse(localStorage.getItem(identifier));
};
// property setter
let setter = function(newVal){
let guardName:string = '__-' + key + '-_can_be_overriden_localStorage';
if((typeof JSON.parse(localStorage.getItem(identifier)) === 'undefined') || JSON.parse(localStorage.getItem(identifier)) == null){
localStorage.setItem(identifier, JSON.stringify(newVal));
} else if ( this[guardName]){
localStorage.setItem(identifier, JSON.stringify(newVal));
}
this[guardName] = true;
};
// Delete property.
if (delete target[key]){
// Create new property with getter and setter
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
}
使用示例:
@Component({...}) class className implements ngOnInit{
...
@Local('storageIdentifier') variable:string = 'default value.';
constructor(){...}
ngOnInit(){
//change value in storage
this.variable = 'some other value';
}
...
}
应该像其他装饰器一样为您工作(输出输入 ViewChild...)
推荐阅读
- amazon-web-services - 通过 Terraform 或 Cloudformation 启用和配置 AWS Cognito 高级安全功能
- ruby-on-rails - Ruby on Rails - 单选内联按钮 - 为什么此选项显示为真/假?
- angular - 我如何将从 post 请求中收到的数据分配给 observable?- 离子3
- javascript - redux-saga 两次调用 - reactjs
- ios - 如何将数据传递给模型类并从模型类中获取数据 - swift
- javascript - Ember addPackageToProject 或 addBowerPackageToProject
- algorithm - 找出到达迷宫任何角落的最小步骤?
- c# - DirectoryEntry CommitChanges() 抛出拒绝访问错误
- java - java - 如何使用数组为Java中的单个字符串分配多个值?
- c++ - 模板扣除投诉模棱两可的候选人