I have a component that displays a list of varieties that are retrieved from a service, as you can see here.
export class SellingMenuVarietiesComponent implements OnInit {
varieties: Variety[];
constructor(public sellingMenuService: SellingMenuService) { }
ngOnInit(): void {
this.getVarietyList();
}
// Get Variety List
getVarietyList(): void {
this.sellingMenuService.getVarieties().subscribe(res => {
this.varieties = res;
});
}
}
I have another component that removes varieties, as seen here:
export class SellingVarietyEditComponent implements OnInit {
constructor(private sellingMenuService: SellingMenuService) { }
// Remove variety
removeVariety(id: number) {
this.sellingMenuService.removeVariety(id).subscribe(res => {
this.sellingMenuService.getVarieties();
});
}
}
In this example, both components are visible on the page at the same time, so when you delete a variety, I want the list to automatically update and reflect that. Currently, the variety will successfully delete from the database, but will remain on the list until I refresh the page. Notice in the removeVariety() function from SellingVarietyEditComponent, I re-invoke the getVarieties() method from my service in an attempt to get the list to update, but it doesn't work.
What am I doing wrong? How Can I accomplish this?
Here are the relevant functions from that service:
@Injectable()
export class SellingMenuService {
// Get Variety List
public getVarieties(): Observable<any> {
return this.http.get(this.varietyList).map(response => {
return response.json();
}, (error: any) => {
console.log(error);
});
}
// Remove Variety
public removeVariety(varietyId: any): Observable<any> {
return this.http.get(this.removeVarietyUrl + varietyId).map(response => {
return response;
}, (error: any) => {
console.log(error);
});
}
}
EDIT:
Attempting EventEmitter solution:
In SellingMenuService, I added this code (Notice I added this.updateVarietyList.emit(null); to getVarieties()):
@Output() updateVarietyList: EventEmitter<any> = new EventEmitter();
// Get Variety List
public getVarieties(): Observable<any> {
return this.http.get(this.varietyList).map(response => {
this.updateVarietyList.emit(null);
return response.json();
}, (error: any) => {
console.log(error);
// TODO: implement error handling here.
});
}
In SellingVarietyEditComponent, my remove button looks like this:
<a class="remove-button" (click)="removeVariety(varietyId)" (updateVarietyList)="onVarietyListUpdate($event)" >Remove</a>
And finally in SellingMenuVarietiesComponent I added this:
onVarietyListUpdate() {
console.log('test');
this.getVarietyList();
}
This code however does not work. I don't get any errors, but the onVarietyListUpdate() method never executes. Am I on the right path at all? How can I fix this? The example I've found are confusing and I am having trouble applying them to my code.