【问题标题】:Display [Object] [Object] in *ngfor Angular 2在 *ngfor Angular 2 中显示 [Object] [Object]
【发布时间】:2018-05-16 00:37:03
【问题描述】:

我正在从 Angular 向控制器发出请求,这是有效的,因为我已经检查了 http 请求,并且响应包含一组对象及其属性。问题是使用 *ngfor 在 html 视图中显示这些对象...我正在使用一个名为 JobsService 的服务:

@Injectable()
export class JobsService {
    private _jobsUrl = 'http://localhost:59164/jobs';
    constructor(private _http: Http) { }

    getJobs(): Observable<Job[]> {
        return this._http.get(this._jobsUrl).map((response: Response) => <Job>response.json())
            .do(data => console.log('All: ' + JSON.parse(JSON.stringify(data)))).catch(this.handleError);
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json() || 'Server error')
    }
}

这是 JobsComponent 类:

import { Component, OnInit } from '@angular/core';
import { JobsService } from './jobs.service';
import { Job } from './job';

@Component({
    templateUrl: './tsScripts/jobs/jobs.component.html',
    providers: [JobsService]
})

export class JobsComponent implements OnInit {
    jobs: Job[] = [];
    errorMessage: string;

    ngOnInit(): void {
        console.log("in OnInit");     
        this._jobsService.getJobs().subscribe(jobs => this.jobs = jobs, error => this.errorMessage = <any>error);
    }  

    constructor(private _jobsService: JobsService) {

    }
}

这是html页面:

<table class="table"> <!--*ngIf="jobs && jobs.length"-->
    <tr *ngFor="let job of jobs">
        <td>{{job.Title}}</td>
    </tr>
</table>

我收到此错误:

尝试区分“[object Object]”时出错。只有数组和可迭代 允许

我认为这是在抱怨,因为期待一个数组并且只是获取一个对象,如果是这种情况,我该如何解决?我以为我组件中的变量jobsJob 类的数组...

以防万一这是Job 类:

export class Job {
    aut_id: number;
    Title: string;
    Description: string;
    AuthorEmail: string;
    Company: string;
    Location: string;
    TypeOfJob: string;
    Salary: number;
    CandidateExperience: string;
    CandidateEducation: string;
    Language: string;
    Approved: string;
}

这是 C# 控制器:

  public JsonResult Index()
        {
            AzureStorageHelper az = new AzureStorageHelper();
            var totalJobs = az.GetJobs();
            var result = totalJobs.Where(j => string.Equals(j.Approved, "Approved", StringComparison.CurrentCultureIgnoreCase));
            var test = result.ToList();
            return Json(new { data = test }, JsonRequestBehavior.AllowGet);  
        }

更新:

【问题讨论】:

  • 如果您在 this._jobsService.getJobs().subscribe(jobs => console.log(jobs)) 中执行 console.log,您在控制台或对象数组中有一系列作业?
  • @mickaelw 对象数组..
  • 我认为您在服务中的映射不正确
  • console.log Json 响应时会得到什么?就像你说的,它似乎只返回一个对象而不是一个数组。

标签: angular angular2-template angular2-services angular2-directives


【解决方案1】:

要转换响应,最好使用接口并将结果映射到自己的类。

我向你推荐这个代码:

@Injectable()
export class JobsService {
  private _jobsUrl = 'http://localhost:59164/jobs';
  constructor(private _http: Http) { }

  getJobs(): Observable<Job[]> {
    return this._http.get(this._jobsUrl).map(response => response.json().map(job => this.mapToJob(job)))
      .do(data => console.log('All: ' + JSON.parse(JSON.stringify(data)))).catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json() || 'Server error')
  }

  private mapToJob(job: JobDTO): Job {
    return new Job(
      +job.aut_id,
      job.Title,
      job.Description,
      job.AuthorEmail,
      job.Company,
      job.Location,
      job.TypeOfJob,
      +job.Salary,
      job.CandidateExperience,
      job.CandidateEducation,
      job.Language,
      job.Approved
    )
  }

}

export class Job{
  aut_id: number;
  Title: string;
  Description: string;
  AuthorEmail: string;
  Company: string;
  Location: string;
  TypeOfJob: string;
  Salary: number;
  CandidateExperience: string;
  CandidateEducation: string;
  Language: string;
  Approved: string;
}


export interface JobDTO{
  aut_id: number;
  Title: string;
  Description: string;
  AuthorEmail: string;
  Company: string;
  Location: string;
  TypeOfJob: string;
  Salary: number;
  CandidateExperience: string;
  CandidateEducation: string;
  Language: string;
  Approved: string;
}

为了转换 API,我使用了一个称为 DTO(数据传输对象)的接口,它有助于构建我的项目所知道的工作。

目前,DTO 和类具有相同的字段,但可能不同。

注意另一件事:response.json().map(job =&gt; this.mapToJob(job)) 因为我认为你的 JSON 返回一个数组?所以,我把它映射成一个 Jobs 数组。

【讨论】:

  • 我复制并粘贴了这段代码,但在创建新的 Job 实例时,mapToJob() 方法出现错误。错误是:Supplied parameters do not match any signature of call target。我认为与被调用时传递给该方法的参数有关...
  • @AlexGH 可以分享一下新服务的截图吗?
  • @michaelw 我已经上传了新错误的截图,很抱歉在我这几天不得不处理不同的东西之前我没有回复你,谢谢
  • @AlexGH 您可以尝试在 job.aut_id 和 job.Salary 之前添加 + 吗?就像我更新的答案一样
  • @michaelw 还是同样的错误。如果我发现了这个问题,我会告诉你的
猜你喜欢
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
相关资源
最近更新 更多