简体   繁体   English

角 | 如何订阅对象数组中的更改

[英]Angular | How to subscribe to changes in array of objects

In my angular application, I have the following array of objects:在我的 angular 应用程序中,我有以下对象数组:

public data = [
{a: 0, b: [{q: 1, z: 2}]}
{a: 1, b: [{q: 4, z: 9}]}
]

Question : How can I subscribe to any changes in the array (also including changes in nested objects)?问题:如何订阅数组中的任何更改(还包括嵌套对象中的更改)?

Expected result : A function that fires every time data is changed预期结果:每次更改data时都会触发的函数

First you need a service to wrap your state (here you can also use more sophisticated frameworks like Redux but lets keep it simply for the start), this is usually a good idea to decouple your application首先你需要一个服务来包装你的状态(在这里你也可以使用更复杂的框架,比如 Redux,但让我们在开始时只保留它),这通常是解耦你的应用程序的好主意

state.service.ts状态.service.ts

import {BehaviorSubject, Observable} from "rxjs/index";
import {Injectable} from "@angular/core";


@Injectable({
    providedIn: 'root',
})
export class StateService {

    private readonly subject: BehaviorSubject<any> = new BehaviorSubject({});

    public readonly observable: Observable<any> = this.subject.asObservable();

    public set(newValue: any): void {
        this.subject.next(newValue);
    }
}

then your component can register to observable to render it eg by using然后您的组件可以注册到observable以呈现它,例如使用

public readonly value: Observable<any> = this.stateService.observable
    .pipe(map(_ => JSON.stringify(_)));

and to eg print out the value并例如打印出值

<p *ngIf="value | async">{{(value | async)}}</p>

and if you are now using set to update the state the component will be refreshed automatically.如果你现在使用set来更新状态,组件将自动刷新。

In general I found Angular applications are way easier to understand if your components and your application state are properly separated (remember Model-View-Controller?) so that your components do not contain any state themselves and are only binding the templates to the state via observables so that you do not need to care about refreshes and updates (remember Java Swing listeners?).一般来说,我发现 Angular 应用程序更容易理解,如果您的组件和您的应用程序状态正确分离(还记得模型-视图-控制器吗?),以便您的组件本身不包含任何状态,并且仅通过以下方式将模板绑定到状态observables 这样你就不需要关心刷新和更新(还记得 Java Swing 监听器吗?)。 And the state has a clearly defined interface to be interacted with so that no one fiddles in the internal structure of your application state.并且状态有一个明确定义的接口来交互,这样就没有人在你的应用程序状态的内部结构中摆弄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM