Essentially, I am working with an Angular component that has a variable called DashboardConfiguration which is set to an Observable. This Observable is obtained from a resolver that utilizes a service to make a GET request for a JSON object.
The issue lies in the fact that the Observable is supplying the variable with a plain Object instead of a DashboardConfiguration object. As a result, I am unable to invoke a function of the DashboardConfiguration.
I have modeled my structure very similarly to this example which includes all code at the end of the article.
The specific DashboardConfiguration class that I need the JSON to be cast to:
export class DashboardConfiguration {
id:string;
createdDate?:any;
properties?:any;
widgets:WidgetConfiguration[];
//This function is not being accessed
public getWidgetByAlias(alias:string):WidgetConfiguration {
this.widgets.forEach(function (widget) {
if(widget.hasAlias(alias)){
console.log("returning widget "+widget.id);
return widget;
}
});
return null;
}
}
The HTTP GET response:
"dashboard": {
"id":"029c2322-8345-4eed-ac9e-8505042967ec",
"createdDate": "",
"properties": {
//omitted form stackoverflow post},
},
"widgets":[
{
"id": "705c0853-e820-4c26-bc4c-e32bd7cb054c",
"createdDate": "",
"properties": {
"aliases":[
"test"
]
}
},
{
"id": "b5e161dd-e85e-44d4-9188-5f4d772d9b40",
"createdDate": "",
"properties": {
"aliases":[
"test1"
]
}
}
]
}
The Angular component:
export class DashboardComponent implements OnInit {
configuration:DashboardConfiguration;
constructor(private route:ActivatedRoute) { }
ngOnInit() {
this.configuration = this.route.snapshot.data['dashboard'];
console.log(this.configuration.id);
}
//The function that calls the non-working function!
getWidgetByAlias(alias:string):WidgetConfiguration {
return this.configuration.getWidgetByAlias(alias);
}
}
The service responsible for the HTTP request:
constructor(private http:HttpClient) {}
getConfiguration(uuid:string):Observable<DashboardConfiguration> {
return this.http.get<DashboardConfiguration>('/api/dashboard',{params: {id: uuid}});
}
The resolver:
constructor(private dashboardService:DashboardService){}
resolve(route: ActivatedRouteSnapshot): Observable<DashboardConfiguration> {
return this.dashboardService.getConfiguration(route.queryParams['id']); //this calls the above service
}