首页 > 解决方案 > 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: enter image description here

Any help on this is highly appreciated.

标签: angular

解决方案


您应该使用 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...)


推荐阅读