在 angular 2 打字稿中将 JSON 转换为通用 Object[] 的最佳方法是什么?

Whats the best way to cast JSON to generic Object[] in angular 2 typescript?

不确定这是否按预期工作,但我想将 json 的 blob 转换为通用对象数组(对象是可塑的,可以根据我的 URL 进行更改)。我应该改用 JSON.parse(res.json().data) 吗?谢谢。

 return this.http.get(URL)
                       .toPromise()
                       .then(response => response.json().data as Object[]) 
                       .catch(this.handleError);
          }

您的解决方案的问题是 Object 类型没有任何成员(通常的成员除外),因此任何试图从您的 JSON 访问特定属性的尝试,例如 id 等会产生错误。

正确的方法是as any[]:

  return this.http.get(URL)
                        .toPromise()
                        .then(response => response.json().data as any[]) 
                        .catch(this.handleError);
           }

这将使您能够访问 JSON 响应中的所有内容(以及 JSON 响应中未包含的所有内容。您将在运行时遇到错误)。 =15=]

最好将结果转换为特定类型,参见How do I cast a JSON object to a typescript class