【发布时间】:2018-03-22 16:11:50
【问题描述】:
请问我如何跟踪/观察服务中的变量或数组以检测其值是否已更改或已添加项目?
【问题讨论】:
-
在您的帖子中添加一些代码,否则您将找不到太多帮助。 stackoverflow.com/help/mcve
请问我如何跟踪/观察服务中的变量或数组以检测其值是否已更改或已添加项目?
【问题讨论】:
问题是您对“跟踪/观看”的最终期望。 例如,您可以将变量放在 Subject 或 BehaviorSubject 中。然后订阅它。每当此主题发生变化时,您都会收到通知。
这是一个例子。
您的服务提供了放在 BehaviorSubject 中的变量“信息”。您可以通过 getter 和 setter 访问此变量。请注意,getter 返回一个 Observable,这对于监控变化很重要。
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
private info = new BehaviorSubject('information');
getInfo(): Observable<string> {
return this.info.asObservable();
}
getInfoValue(): string {
return this.info.getValue();
}
setInfo(val: string) {
this.info.next(val);
}
}
在您的组件中,您执行以下操作
import { MyService } from 'my.service';
constructor(
private myService: MyService
) {
/**
* whenever your variable info inside the service changes
* this subscription will get an event and immediately call the code
* inside.
*/
this.myService.getInfo().subscribe(value => {
// do something with this value
console.log('Info got changed to: ', value);
});
}
这是监控服务内变量变化的最佳方式。
【讨论】: