角度集全局变量

时间:2019-01-31 10:34:43

标签: angular typescript

打开应用程序时,我试图基于字符串将Global变量设置为其他值。

globals.ts

import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
  env: string;
  constructor() {}
  setEnv(setEnv: string) {
    this.env = setEnv;
  }
}

cti-nav.component.ts

import {Component, Inject, OnInit} from '@angular/core';
import {ListService} from '../../assets/list/list.service';
import {Globals} from '../globals';

export class CtiNavComponent implements OnInit {
    tools = this._ListService.getList(this.globals.env);  //<= returns undefined
    ngOnInit() {
        this.globals.setEnv('int');
        console.log(this.globals.env);  //<= returns int
    }
    constructor(private _ListService: ListService, private globals: Globals) {}
}

cti-nav.module.ts

import {Globals} from '../globals';

@NgModule({
    providers: [Globals]
})
export class CtiNavModule {}

list.service.ts

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class ListService {
  constructor(private http: HttpClient) {}

  getList(env) {
    return this.http.get('https://list.url.com/' + env);
  }
}

当我检查日志时,它会正确输出int,然后在_ListService部分中,它返回undefined。正确的是_ListService是否也返回int。

2 个答案:

答案 0 :(得分:3)

ngOnInit将在构造函数和工具之类的属性初始化之后被调用。初始化全局变量后,您将必须重新处理逻辑以初始化工具。也许您可以通过在构造函数中调用setEnv而不是ngOnInit

来尝试

答案 1 :(得分:2)

真的可以将您的this._ListService.getList(this.globals.env);移至构造函数或ngOnInit

  import {Component, Inject, OnInit} from '@angular/core';
    import {ListService} from '../../assets/list/list.service';
    import {Globals} from '../globals';

        export class CtiNavComponent implements OnInit {
            tools; 
            ngOnInit() {
                this.globals.setEnv('int');
                console.log(this.globals.env);  //<= returns int
            }
            constructor(private _ListService: ListService, private globals: Globals) {
            this._ListService.getList(this.globals.env);  //try to move here
        }
        }