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
export class UserManagementService extends RestService {
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);
}
getEapGroupList(): Observable < EapGroupInterface > {
return this.get < GroupInterface >
(this.getFullUrl(`${this.BASE_URL_UM}/groups`), {
headers: this.headers
});
}
updateGroup(body: CreateGroupPayload): Observable < CreateGroupPayload > {
return this.put < GroupPayload >
(this.getFullUrl(`${this.BASE_URL_UM}/group`), body, {
headers: this.headers
});
}
}
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
There is a lot of example on the web, you can use "Subject" and Output EventEmitter. Both will work. The following example is the sample code of shared service. Try to use it.
Create an
@Injectable
service class with a Subject in it. Have both components look at this service class subject to see what to do when. One class can call .next() on the subject and the other can subscribe to it and call it's own function when it gets an update.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:
Then each time that the data changes, Angular's dependency injection will automatically call the getter and get the most recent values.
Revised service
Revised component 1
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)