I have an angular component with a simple service that extracts some data based on a parameter which happens to be an Enum.
export enum AgeEnum {
UNDER_18 = 'UNDER_18',
ABOVE_18 = 'ABOVE_18'
}
Then in my component I have the following:
private ageArray = Object.keys(AgeEnum);
private restrictionsWrapper: RestrictionsWrapper;
constructor(private restrictionsService: RestrictionsService) {
}
ngOnInit(): void {
this.getRestrictionsForAge(this.ageArray);
}
private getRestrictionsForAge(ages: string[]) {
for (const age of ages) {
this.restrictionsService.getRestrictions(age as AgeEnum)
.subscribe((options) => {
this.restrictionsWrapper.restrictions = options.restrictions;
}, () => {
this.restrictionsWrapper.restrictions = null;
}
);
}
}
My UI Service looks like this:
getRestrictions(age: AgeEnum): Observable<RestrictionsWrapper> {
const params = new HttpParams().set('age', age);
return this.http.get<RestrictionsWrapper>(BackendRoute.RESTRICTIONS, {params: params});
}
And this is my RestrictionsWrapper model:
export interface RestrictionsWrapper {
restrictionDocuments: string[];
blocked: boolean;
}
So basically, based on the age, i want to load a different set of 'restrictions'. But I don't want to have two separate methods where I pass two different ENUM values for each. I am getting an error:
Unhandled error occured. TypeError: Cannot set property 'restrictions' of undefined
Any idea what I am doing wrong? Is this actually correct (or good practice) this.restrictionsService.getRestrictions(age as AgeEnum) ?
restrictionsWrappersomewhere? Because it looks like you're not doing this and that would be the cause for your error message.