如何在angular2中更新全局变量 [英] How to Update Global variable in angular2
问题描述
Am使用angular2.对于全局变量访问,我创建一个服务并注入到我的组件页面中.
Am using angular2. For the global variable access I create a service and inject into my component pages.
我可以在任何页面上访问它,但是当我更新该变量时,在另一个页面中访问它时所做的更改将不会受到影响.
I can acces it any page , but when I update that variable the changes will not affect while accessing it in another page.
这是GlobaldataService中的代码
This is the code in the GlobaldataService
import { Injectable } from '@angular/core';
@Injectable()
export class GlobaldataService {
public var1="haii";
}
这是我使用的服务.
This is the service that I used .
constructor(public obj: GlobaldataService){}
在我的组件页面之一中,我通过this.obj.var1 ="hello";
In one of my component page , I update the variable by this.obj.var1 =" hello";
在另一个页面组件警报中(this.obj.var1);但是它显示了较旧的值"haii",该值如何更新全局变量.
in another page component alert(this.obj.var1); But it dispalys the older value which is "haii" how can update the global variable .
预先感谢
推荐答案
您想要的是Messenger服务.它保留了一个全局变量,并为您的组件提供了Observable
可供订阅以及一种更新和广播新值的方法:
What you want is a messenger service. It's keeping a global variable and offers your components an Observable
to subscribe to as well as a method to update and broadcast a new value:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject ';
import { Observable } from 'rxjs/Observable ';
@Injectable()
export class MessengerService {
private messageSource: BehaviorSubject<string> = new BehaviorSubject('initialValue');
public message = this.messageSource.asObservable();
public setMessage(value: string) {
this.messageSource.next(value);
}
}
在您的组件中,您只需订阅该值并可以对其进行更新:
In your component, you're simply subscribing to the value and can update it:
import { Subscription } from 'rxjs/BehaviorSubject ';
export class ViewComponent implements OnInit, OnDestroy {
private messageSubscription: Subscription;
constructor(private messengerService: MessengerService) { }
ngOnInit() {
this.messageSubscription = this.messengerService.message.subscribe(m => {
// Do something with your value
});
}
ngOnDestroy() {
this.messageSubscription.unsubscribe();
}
setGlobalValue(value: string) {
// All components that are subscribed to the
// messenger service receive the update
this.messengerService.setMessage(value);
}
}
这篇关于如何在angular2中更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!