I'm having troubles to understand how I should work with Observables to meet my requirements. As an example, lets say that I have an application and for internationalization, I'm using REST service with all the labels and translations. Some labels can change based on performed actions on the page. And I'm not sure how to retrieve data from the service and use it in different methods.
Let's look at this pseudo-code:
labels: KeyValuePair[];
userDetails: UserDetails;
displayedColumns: string[];
// services below generated thanks to ng-swagger-gen
constructor(
labelService: LabelService,
userService: UserService
){}
ngOnInit() {
this.userService.get().subscribe(
(userData) => {
this.userDetails = userData;
console.log(userData);
},
(error) => {
this.errorMessage = error;
}
);
this.labelService.get(this.userDetails.getLanguage()).subscribe(
(labelsResponse) => {
this.labels = labelsResponse; // use the labels in HTML template
console.log(labelsResponse);
},
(error) => {
this.errorMessage = error;
}
);
this.retrieveTableColumns();
}
retrieveTableColumns() {
this.displayedColumns = this.labels.filter(/* filter columns */);
}
executeMethods() { // method executed from HTML template
this.doSomethingWithUserDetails();
this.doSomethingWithLabels();
}
doSomethingWithUserDetails() {
// 1. do differnet things and use it in HTML template
// 2. check one of properties and based on this
this.setColumns();
}
setColumns() { // columns used in mat-table
if (this.userDetails.allowedForAction) {
this.displayedColumns = this.columnsDef.concat(['action']);
this.hiddenColumns.push(this.displayedColumns.length);
} else {
this.displayedColumns = this.columnsDef;
}
}
doSomethingWithLabels() {
// do some magic using retrieved labels
}
For generating web client service, I've used ng-swagger-gen.
How to handle the Observables to achieve this? So to be able to use data in different places. I've heard about converting it with .toPromise and use async await, but I've also heard that this is antipattern... So not sure what to do here... I'm working with Angular 9 if it matters.