Angular全局变量使用

这里介绍一种使用service来实现全局变量的方法

创建一个SessionService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root',
})
export class SessionService {

private globalContext = {}

constructor() {}

getGlobal(key: string, defaultData?: {}) {
if (!this.globalContext[key]) {
this.globalContext[key] = defaultData || {};
}
return this.globalContext[key];
}
}

session中有一个全局上下文, 在组件中通过key获取全局域

组件中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14

@Component({
templateUrl: "test.component.html"
})
export class TestComponent {

private global = {
user: {},
};

constructor(private session: SessionService) {
this.data.global = this.session.getGlobal("TEST", this.data.global);
}
}

只需要在初始化的使用session.getGlobal(), private global里的内容就是全局的了, 多次载入组件内容保持一致