Angular:将json get响应转换为具有函数的类

时间:2018-07-24 18:43:33

标签: angular typescript angular-observable

所以基本上,我有一个Angular组件,该组件的DashboardConfiguration类型的变量被设置为Observable。这个可观察到的结果来自解析程序,该解析程序调用对json对象进行get请求的服务。

问题在于,可观察对象将变量提供给普通对象,而不是DashboardConfiguration对象。这使我无法调用DashboardConfiguration函数。

我将其构造为非常相似的to this example,其所有代码都位于文章底部

DashboardConfiguration类,我需要将json强制转换为

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"
            ]
          }
        }
      ]
  }

Angular组件:

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
  }

2 个答案:

答案 0 :(得分:1)

简短的答案是HttpClient服务将为您执行此操作。如您所说,它以类属性的形式返回一个JavaScript对象,而不是该类的实际实例。

您需要添加自己的代码来创建正确类型的对象。

这里有一个示例:Angular2. Map http response to concrete object instance

答案 1 :(得分:1)

您可以将json数据与新创建的对象结合使用,当我想对api响应数据使用任何类型的功能时,都可以使用它。

使用地图运算符

this.http.get<DashboardConfiguration>('/api/dashboard',{params: {id: uuid}})
  .map(result => Object.assign(new DashboardConfiguration(),result));

Object.assign()