0

I have data response as object:

let response = {
   attachments: [{id: 1}, {id: 2}, {id: 3}]
}

I use this data in root component <app-root></app-root>

<app-documents [response]="response"></app-documents>
<app-attachments [response]="response"></app-attachmnets>

Inside component app-documents I try to update response:

response.attachments.push({id: 4});

But in app-attachments component that uses the same response object is not changed.

How to fix it?

  • Does this answer your question? [Angular 2: How to detect changes in an array? (@input property)](https://stackoverflow.com/questions/42962394/angular-2-how-to-detect-changes-in-an-array-input-property) – Roy Sep 18 '20 at 09:12
  • No, I need to detect chnages in another component, so I can to add `response` to service then share service bettwen components –  Sep 18 '20 at 09:14
  • This halped me ` this.application.attachments = [].concat(this.application.attachments);` –  Sep 18 '20 at 09:16
  • You use your array on input, so to get changes you need to make it on output too : https://angular.io/guide/inputs-outputs – user7867717 Sep 18 '20 at 09:16

1 Answers1

0

That's because you are making an unilateral assignment to your response variable. I.e. app-attachments response won't detect changes made in another component.

You can either:

  1. Use some state management tool like ngrx which I think it is not the better solution for you right now because it requires redux knowledge and has a significant boilerplate;
  2. Use a simple service wich allows you to share your response across components.

Example:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ResponseService {
  responseSubject: BehaviorSubject<any>;

  constructor() {
    this.responseSubject = new BehaviorSubject(null);
  }

  getResponseValue(): any {
    return this.responseSubject.getValue();
  }

  setResponse(response: any): void {
      this.responseSubject.next(response);
  }

  addItem(item: any): void {
    this.responseSubject.next([...this.responseSubject.getValue(), item]);
  }
}

For usage in your components:

// Get current response array value
let response = this.responseService.getResponseValue();

// Set response value(for example, when you receive it from an API)
this.responseService.setResponse([{id: 1}, {id: 2}, {id: 3}]);

// To push new item to attachments array
this.responseService.addItem({id: 4});
F.Almeida
  • 413
  • 2
  • 12