在我的 Angular2 应用程序中,我有一个具有类似以下属性的对象:
var person = {
firstname:"Tom",
lastname:"Hanks"
};
如果这些属性之一,例如“firstname”更改为“Bill”,我想隐藏 HTML 页面中的某些元素。 有没有办法观察这个物体的变化?使用 RxJS 执行此操作的最佳方法是什么?我是 Angular 和 RxJS 的新手。
答案 0 :(得分:2)
您可以通过 distinctUntilKeyChanged
观察对象属性
distinctUntilKeyChanged
- 仅当指定的键值具有
改变了
示例:
console.clear();
import { BehaviorSubject } from "rxjs";
import { distinctUntilKeyChanged } from "rxjs/operators";
const personSrc = new BehaviorSubject<any>({
firstname: "Tom",
lastname: "Hanks"
});
setTimeout(() => {
const newPerson = { firstname: "Bill", lastname: "Smith" };
personSrc.next(newPerson);
}, 5000);
personSrc.pipe(distinctUntilKeyChanged("firstname")).subscribe(console.log);
当 firstname
的值改变时,它会发出一个新值
演示:https://stackblitz.com/edit/rxjs-distinct-example-a7t4jk?file=index.ts
答案 1 :(得分:0)
您可以使用主题。
export class YourService {
person$: Subject<Person> = new Subject<Person>();
setPerson(person) {
this.person$.emit(person);
};
}
你的组件:
constructor(
private yourService: YourService
) {}
ngOnInit() {
this.yourService.person$.subscribe(person => {
// here you get the new data
});
}
changePersonName() {
this.person.firstName = 'Bill';
this.yourService.setPerson(this.person); // this will fire the person$ Subject
}
答案 2 :(得分:0)
BehaviorSubject
。控制器
const personSrc = new BehaviorSubject<any>({
firstname:"Tom",
lastname:"Hanks"
};
const person$ = this.personSrc.asObservable();
async
管道将其显示在模板中。模板
<ng-container *ngIf="(person$ | async) as person">
<span *ngIf="person['firstname'] !== 'Bill'">
{{ person.lastname }}
Some properties
<span>
</ng-container>
控制器
this.personSrc.next({firstname: "Bill", lastname: "Watterson"})