Home > front end >  DOM tree is not redrawn after calling a function from another component
DOM tree is not redrawn after calling a function from another component

Time:03-10

I have a component where I display users.

users.component.ts:

dataSource!: any;

ngOnInit(): void {
  this.load();
}

load(): void {
  this.loading = true;
  this.usersService.all()
    .pipe(takeUntil(this.destroy$))
    .subscribe(
      (data) => {
        this.loading = false;
        this.dataSource = data
        console.log(this.dataSource)
      }, error => {
        this.loading = false;
        this.toastr.error(
          error.error.message,
          error.status   ' '   error.statusText
        );
      })
}

users.component.html:

<div *ngFor="let user of dataSource">
    {{user.name}}
</div>

I also have a modal window that allows you to add a new user.

After saving, the new user should be displayed.

But it doesn't happen.

add.component.ts:

  constructor(
    public modal: NgbActiveModal,
    private comp: UsersComponent
  ) { }

 send(): void {
    ...
      this.comp.load();
    ...
 }

CodePudding user response:

Use an EventEmitter inside the UsersService to communicate the components:
Working stackblitz example

users.service

import { EventEmitter, ... } from '@angular/core';

@Injectable()
export class UsersService {
  reloadUsers = new EventEmitter<void>();
  ...

users.component.ts

ngOnInit() {
...
this.usersService.reloadUsers
  .pipe(takeUntil(this.destroy$))
  .subscribe(() => {
    this.load();
  });
}

add.component.ts

send(): void {
  ...
  this.usersService.reloadUsers.emit();
  ...
}
  • Related