所以基本上我有一个 Angular 组件,它有一个 DashboardConfiguration 类型的变量,它被设置为一个 Observable。这个 observable 来自一个解析器,它调用一个对 json 对象发出 get 请求的服务。
问题是 observable 正在为变量提供一个普通对象,而不是 DashboardConfiguration 对象。这使我无法调用 DashboardConfiguration 的函数。
我将其结构与此示例非常相似,该示例的所有代码都在文章的底部
我需要将 json 转换为的 DashboardConfiguration 类
export class DashboardConfiguration {
id:string;
createdDate?:any;
properties?:any;
widgets:WidgetConfiguration[];
//This is the function that is not being called
public getWidgetByAlias(alias:string):WidgetConfiguration {
this.widgets.forEach(function (widget) {
if(widget.hasAlias(alias)){
console.log("returining widget "+widget.id);
return widget;
}
});
return null;
}
}
http-get 响应:
"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"
]
}
}
]
}
角组件:
export class DashboardComponent implements OnInit {
configuration:DashboardConfiguration;
constructor(private route:ActivatedRoute) { }
ngOnInit() {
this.configuration = this.route.snapshot.data['dashboard'];
console.log(this.configuration.id);
}
//This is the function calling the function thats not working!
getWidgetByAlias(alias:string):WidgetConfiguration {
return this.configuration.getWidgetByAlias(alias);
}
}
发出 http 请求的服务:
constructor(private http:HttpClient) {}
getConfiguration(uuid:string):Observable<DashboardConfiguration> {
return this.http.get<DashboardConfiguration>('/api/dashboard',{params: {id: uuid}});
}
解析器:
constructor(private dashboardService:DashboardService){}
resolve(route: ActivatedRouteSnapshot): Observable<DashboardConfiguration> {
return this.dashboardService.getConfiguration(route.queryParams['id']); //this calls the service above
}