页面参考上的页面丢失全局var值/浏览器重新加载

时间:2019-11-22 15:43:08

标签: angular

从菜单中调用时,我的页面工作正常。...加载到ngOnInit上的全局变量用于将国家/地区列表填充到选择控件中,并且工作正常。但是观察到,当我通过浏览器刷新重新加载页面时,全局值变为空,因此下拉列表也为空。 服务获取国家列表:

@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;
}
}

国家/地区会在模块初始化时加载。.此模块中的我的组件在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)
 }

除浏览器刷新外,以上均能正常工作。

页面引用页面上的控制台消息如下: enter image description here

对此提供任何帮助,我们深表感谢。

1 个答案:

答案 0 :(得分:1)

您应该使用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';
    }
    ...
}

应该像其他装饰器一样为您工作(Output Input ViewChild ...)