angular 全局监听变量
提供了一个使用 `BehaviorSubject` 的 `Store` 服务的简化示例。这是一个非常基本的状态管理模式,常见于 Angular 应用中。 创建store.js
代码概述:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class Store {
// 游戏大种类id
public game_type: BehaviorSubject<any[]> = new BehaviorSubject([]);
constructor() {}
}
在其他文件中,你可以更新 `game_type` 的值:
this.store.game_type.next(data['game_type']);也可以订阅这个值的更改:
public sub_game_type: Subscription;
this.sub_game_type = this.store.game_type.subscribe(data => {
if(data) {
// do something with the updated data
}
});
最后,当组件被销毁时,为了避免内存泄漏,你取消了对 `game_type` 更改的订阅:
ngOnDestroy() {
this.sub_game_type.unsubscribe();
}
浙公网安备 33010602011771号