Angular 7 - Reload / refresh data different components

SKL picture SKL · Feb 19, 2019 · Viewed 12.8k times · Source

How to refresh data in different component 1 when changes made in component 2. These two components are not under same parentnode.

customer.service.ts

Component1.ts

export class UserGroupComponent implements OnInit {

  constructor(private userManagementService: UserManagementService) {}

  ngOnInit() {
    this.loadGroup();
  }

  loadGroup() {
    this.userManagementService.getEapGroupList()
      .subscribe(response => {
        this.groups = response;
      })
  }

}
<mat-list-item *ngFor="let group of groups?.groupList" role="listitem">
  <div matLine [routerLink]="['/portal/user-management/group', group.groupCode, 'overview']" [routerLinkActive]="['is-active']">
    {{group.groupName}}
  </div>
</mat-list-item>
<mat-sidenav-content>
  <router-outlet></router-outlet>
</mat-sidenav-content>

component2.ts

setPayload() {
  const formValue = this.newGroupForm.value
  return {
    'id': '5c47b24918a17c0001aa7df4',
    'groupName': formValue.groupName,
  }
}

onUpdateGroup() {
    this.userManagementService.updateGroup(this.setPayload())
      .subscribe(() => {
          console.log('success);
          })
      }

When I update onUpdateGroup() api in component1, loadGroup() should refresh in component2

Answer

DeborahK picture DeborahK · Feb 19, 2019

Move the code that retrieves the data to the service so the service maintains the groups.

Then wrap that data in Component 1 in a getter:

get groups() {
  return this.userManagementService.groups
}

Then each time that the data changes, Angular's dependency injection will automatically call the getter and get the most recent values.

Revised service

export class UserManagementService extends RestService {
  groups;
  private BASE_URL_UM: string = '/portal/admin';

  private headers = new HttpHeaders({
    'Authorization': localStorage.getItem('token'),
    'Content-Type': 'application/json'
  });

  constructor(protected injector: Injector,
    protected httpClient: HttpClient) {
    super(injector);

    // Get the data here in the service
    this.loadGroup();
  }

  getEapGroupList(): Observable < EapGroupInterface > {
    return this.get < GroupInterface >
      (this.getFullUrl(`${this.BASE_URL_UM}/groups`), {
        headers: this.headers
      });
  }

  loadGroup() {
    this.getEapGroupList()
      .subscribe(response => {
        this.groups = response;
      })
  }

  updateGroup(body: CreateGroupPayload): Observable < CreateGroupPayload > {
    return this.put < GroupPayload >
      (this.getFullUrl(`${this.BASE_URL_UM}/group`), body, {
        headers: this.headers
      }).pipe(
         // Reget the data after the update
         tap(() => this.loadGroup()
      );
  }
}

Revised component 1

export class UserGroupComponent implements OnInit {
    get groups() {
      return this.userManagementService.groups
    }

  constructor(private userManagementService: UserManagementService) {}

  ngOnInit() {

  }
}

NOTE: This code was not syntax checked!

I have a similar working example here: https://github.com/DeborahK/Angular-Communication/tree/master/APM-FinalWithGetters

(Check out the product-shell folder files along with the product.service.ts)