Angular2:将对象转换为json文件的数组

时间:2016-10-27 16:54:40

标签: json angular ngfor

我正在尝试从JSON加载一个对象数组,并在我的angular2应用中使用* ngFor在我的模板中显示它们。我收到此错误Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

我已经找到了关于这个特定错误和修复的相当多的文档,但是我无法理解/将其转换为工作修复。根据我的理解,* ngFor只会渲染数据数组,而我的home.component正在尝试渲染数组对象。

我读过的修补程序是写一个这样的管道:

@Pipe({ name: 'values',  pure: false })
export class ValuesPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key]);
  }
}

我已经尝试了这个,但后来我收到一条错误,上面写着compiler.umd.js?9df7:14126Uncaught Error: Unexpected value 'HomeComponent' declared by the module 'AppModule'我已经将管道直接构建到我的家庭组件中,所以我不确定为什么这是一个问题。

这是我的代码。

home.component.js

    import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';
import { Project } from './project';

import { ProjectService } from './project.service';

@Component({
  selector: 'home',
  templateUrl: './home.html',
  styleUrls: ['./home.scss'],
  providers: [ProjectService]
})

@Pipe({ name: 'values',  pure: false })
export class ValuesPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key]);
  }
}

export class HomeComponent implements OnInit {
  errorMessage: string;
  projects: Project[];
  selectedProject: Project;
  mode = 'Observable';

  constructor(private projectService: ProjectService) { }

  ngOnInit() { this.getProjects(); }

  getProjects() {
    this.projectService.getProjects()
      .subscribe(
      projects => this.projects = projects,
      error => this.errorMessage = <any>error);
  }

  onSelect(project: Project): void {
    this.selectedProject = project;
  }
}

projects.service.js

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';

import { Project } from './project';
import { Observable }     from 'rxjs/Observable';


@Injectable()
export class ProjectService {
  private projectsUrl = 'data/project.json'; // URL to web API

  constructor(private http: Http) { }

  getProjects(): Observable<Project[]> {
    return this.http.get(this.projectsUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.data || {};
  }

  private handleError(error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

project.json

 {
  "project": [{
    "title": "The Upper Crust",
    "id": "upper-crust",
    "year": "2016",
    "category": ["Design", "Web Design"],
    "thumbnail": "thumbnails/upper-crust.jpg"
  }, (...)
}

很抱歉,如果答案已经在那里,我昨晚花了几个小时,今天早上试图解决这个问题,似乎无法搞清楚。我提前感谢你的帮助,我是发展的新手,并且对这些东西感到很茫然。

0 个答案:

没有答案