【发布时间】:2018-04-21 22:29:25
【问题描述】:
我是 Angular 的新手,我主要使用 VueJS。我想知道如何检测变量何时更新。我正在通过 DataService 更新我的变量。我阅读了有关 ngOnChanges() 的信息,但我发现这仅适用于输入。
这几乎是我的代码:
import { DataService } from "../../service/my.service";
export class MainPage {
myVar: String = ""; // this is the variable I want to listen when a change is made
constructor (
private data: DataService
) {}
ngOnInit() {
this.data.changeVar.subscribe(message => this.myVar = message);
}
}
我的服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject<string>("");
changeVar = this.messageSource.asObservable();
constructor() { }
changeMyVar (message: string) {
this.messageSource.next(message)
}
}
这是我更新变量的地方。
import { DataService } from "../../service/my.service";
export class AnotherPage {
anotherVar: String = '';
constructor(
private data: DataService
) { }
ngOnInit() {
this.data.changeVar.subscribe(message => this.anotherVar = message)
}
myFunction () {
this.data.changeMyVar("Hello"); // update variable to "Hello"
}
}
非常感谢任何帮助! :)
【问题讨论】:
-
由于您在 Observable 回调中为
myVar分配了一个新值,因此您知道它何时发生变化。您还想获得哪些其他信息? -
当变量的值发生变化时,我想在 MainPage 中运行一个函数。
标签: angular typescript