Home > Blockchain >  Why stream is not emitting changes?
Why stream is not emitting changes?

Time:11-03

There is a subject users$, which is displayed in the template via async

Why, when I toggle the checkbox and changing user.checked - the data is not shown in the subscription console.log()

<div *ngFor="let user of users$ | async">
     <mat-checkbox [(ngModel)] = "user.checked"></mat-checkbox>
</div>


public users$: Observable<User[]>;
this.users$ = this.securityService.users$; // users$ in service it is behSubject
        this.checkedUsersId$ = this.users$.pipe(map((users) => users.filter((user) => user.checked).map((u) => u.id)));
        this.checkedUsersId$.subscribe((e) => console.log(e));
    }

I need to filter all checked users.

How to say to stream that object was changed?

CodePudding user response:

Your are setting the property of a emitted value from user$, this does not update the stream itself.

To update the stream you need to send the update to the component/service holding the subject, a simplified example looks like this:

import { Component, VERSION } from '@angular/core';
import { BehaviorSubject, Subject, Observable } from 'rxjs';

@Component({
  selector: 'my-app',
  template: `
    <div *ngFor="let user of users$ | async">
      Checked: {{user.checked}}
      <mat-checkbox [ngModel]="user.checked" (ngModelChange)="updateUser(user.id, !user.checked)"></mat-checkbox>
    </div>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular '   VERSION.major;

  private users = [{ id: 1, checked: false }];

  public userSubject: Subject<{ id: number; checked: boolean }[]> =
    new BehaviorSubject(this.users);
  public users$: Observable<{ id: number; checked: boolean }[]> =
    this.userSubject.asObservable();

  public updateUser(id: number, checked: boolean) {
    this.users = this.users.map((user) =>
      user.id === id ? { ...user, checked } : user
    );
    // Send update to stream.
    this.userSubject.next(this.users);
  }
}

For you this probably means your service must have a method to update users, I tried to keep it simple here to bring the point across.

  • Related