使用Angular观察对象特性中的更改



在我的Angular2应用程序中,我有一个具有类似属性的对象:

var person = { 
firstname:"Tom", 
lastname:"Hanks" 
};

如果这些性质中的一个;名字";更改为";Bill";,我想在HTML页面中隐藏一些元素。有什么方法可以观察这个物体的变化吗?使用RxJS最好的方法是什么?我是Angular和RxJS的新手。

您可以通过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

您可以使用主题。

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
}
  1. 将对象封装在类似BehaviorSubject的多播可观察对象中

控制器

const personSrc = new BehaviorSubject<any>({ 
firstname:"Tom", 
lastname:"Hanks" 
};
const person$ = this.personSrc.asObservable();
  1. 使用async管道在模板中显示它

模板

<ng-container *ngIf="(person$ | async) as person">
<span *ngIf="person['firstname'] !== 'Bill'">
{{ person.lastname }}
Some properties
<span>
</ng-container>
  1. 通过可观察对象推动对对象的任何更改

控制器

this.personSrc.next({firstname: "Bill", lastname: "Watterson"})

最新更新