请如何跟踪/观察服务中的变量或数组,以检测其值是否已更改或项目是否已添加?
答案 0 :(得分:2)
问题是你最终期望从“追踪/观看”中得到什么。 例如,您可以将变量放在Subject或BehaviorSubject中。然后订阅它。每当此主题发生变化时,您都会收到通知。
这是一个例子。
您的服务提供变量'info',它放在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);
});
}
这是监控服务内变量变化的最佳方式。