如何从api获取JSON数组对象值?

时间:2019-02-22 10:48:35

标签: angular typescript api

我正在尝试显示api的Arrrry值。但我遇到以下错误。如何解决此错误?

错误

Error which i get in console

代码如下:

joblist.service.ts

import { Injectable } from '@angular/core';

import { HttpClient} from '@angular/common/http';

import { Observable } from 'rxjs';

import { IJobs } from '../jobs';


@Injectable({
  providedIn: 'root'
})
export class JoblistService {

 private _url: any = 'http://13.126.181.94:8087/joblisting.php? 
action=filter/';

constructor(private http: HttpClient) { }

getjoblists(): Observable<IJobs[]> {
return this.http.get<IJobs[]>(this._url);
}
}

joblist.component.ts

import { Component, OnInit } from '@angular/core';

import { JoblistService } from 'src/app/joblist/joblist.service';


@Component({

selector: 'app-joblist',

template: `
 <h2>Job Title</h2>
 <ul *ngFor='let joblist of joblists'>
 <li>
   {{joblist.job_title}} - {{joblist.job_id}} - {{joblist.job_add_date}} -
   {{joblist.date_diff}} - {{joblist.role}} - {{joblist.clientname}} -
   {{joblist.location}} - {{joblist.experience}} - {{joblist.salary}} -
   {{joblist.job_offer_type}} - {{joblist.companies_profiles_name}} - 
   {{joblist.job_description}} - {{joblist.skill_name}}
 </li>
 </ul>
  `,
 styles: []
 })


export class JoblistComponent implements OnInit {

public joblists = [];

constructor(public _joblistsService: JoblistService) { }

ngOnInit()
  {

 this._joblistsService. getjoblists()
 .subscribe(data => this.joblists = data);
   } }

jobs.ts

导出类IJobs

{

 job_title: string;

 job_id: number;

 job_add_date: Date;

 date_diff: number;

 role: string;

 clientname: string;

 location: string;

 experience: string;

 salary: string;

 job_offer_type: number;

 companies_profiles_name: string;

 job_description: string;

 skill_name: string;

}

在控制台中,我可以按如下方式获取obj。

enter image description here

2 个答案:

答案 0 :(得分:1)

替换-

<ul *ngFor='let joblist of joblists'>

使用

 <ul *ngFor='let joblist of joblists?.all_search_view'>

当您尝试在数组上使用*ngFor时,但是您正在与对象绑定。

答案 1 :(得分:0)

首先,在joblist.service.ts

this.http.get<IJobs[]>(this._url);

由于您的响应不只是IJOBs[],因此应将其替换为期望的响应正文的结构。因此,当您在component.ts中分配值时,打字稿将自动为您显示错误。

要使其工作,您可以更改结构,如我提到的那样或@Pardeep Jain指出。两者都可以。