繁体   English   中英

如何从 Angular 2 中的 JSON 数据获取数组

[英]How to get an array from JSON data in Angular 2

我正在 angular 2 中开发一个应用程序。我创建了一个服务,现在我想从 json 数据中获取特定的数组,我可以如何获取。

我有这样的服务代码

getProjects(): Promise<Project>{
return this.getData()
  .toPromise()
  .then(response => response.json())
  .catch((error: string) => console.log(error));
}

这将返回所有 json 数据,但我只想从 json 中获取“Projects”数组。

JSON 代码

{
   "features":[],
   "posts":{},
   "Projects":[
    {
        "id":"proj-1",
        "name":"Design for creative",
        "meta":{
            "date":"03 November, 2016",
            "url":"http://www.pixelsocket.com",
            "skills":[
                "ui design",
                "programming",
                "marketing"
            ]
        },
        "images":[
            "assets/images/design-creative-01.jpg",
            "assets/images/design-creative-02.jpg",
            "assets/images/design-creative-03.jpg",
            "assets/images/design-creative-04.jpg"
        ],
        ...
}

更新

getProject(id: string): Promise<Project>{
 const url = `${this.getProjects()}/${id}`; // can i call getProjects() method here

 return this.http.get(url)
   .toPromise()
   .then(response => response.json())
   .catch((error: string) => console.log(error));
}

使用一种方法来转换json,

private extractData(res: any) {
        if (res.status < 200 || res.status >= 300) {
            throw new Error('Bad response sttus:' + res.status);
        }
        let serviceData = res.json().projects;
        return serviceData || {};
    }

getProjects(): Promise<Project>{
return this.getData()
  .toPromise()
  .map(this.extractData);
}
getProjects(): Promise<Project>{
return this.getData()
  .toPromise()
  .then(response => response.json().projects) // <<< added .projects
  .catch((error: string) => console.log(error));
}
getProject(id: string): Promise<Project>{
  return this.getProjects()
  .then(p => `${p}/${id}`) // no idea where `id` should come from
  .then(url => {
    return this.http.get(url)
   .toPromise()
   .then(response => response.json())
   .catch((error: string) => console.log(error));
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM