如何在角度2中获得数据复杂的json响应?

时间:2017-06-08 09:48:01

标签: angular angular2-services

我有一个预订列表页面。我试图从json文件中获取数据。在第一种格式结果中,但第二种格式数据未获得。我在下面解释了两种格式。请帮我解决这个问题。我在plunker中添加了我的代码。

Plunker Link

第一

    [
       {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
       },
       {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
       },
       { "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
       },
      {
       "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
       }
   ]

第二

{
  "bookingDetails": {
    "data": [
      {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
      }
    ]
  }
}

apidata - >中包含Json文件testData.json

app - >预订 - > booking.service.ts

getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .toPromise()
            .then(response => response.json() as Bookings[])
            .catch(this.handleError);
    }

app - &gt;预订 - &gt; booking.component.ts

export class BookingComponent implements OnInit {
    bookings: Bookings[];
    constructor(private employeeService: BookingService) {}
    getBooking(): void {
        /*this.employeeService.getEmployee().then(employees => this.employees = employees);*/
        this.employeeService.getBooking().then(bookings => this.bookings = bookings);
    }
    ngOnInit(): void {
        this.getBooking();
    }
}

2 个答案:

答案 0 :(得分:0)

您的plunker有错误,但您需要更正您的服务实施以及您在angular2中使用它的方式。

更改 booking.service.ts 代码,例如:

getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .map(response => response.json().bookingDetails.data as Bookings[])
            .catch(this.handleError);
    }

booking.component.ts 中的代码,例如:

this.employeeService.getBooking().subscribe(bookings => this.bookings = bookings );

答案 1 :(得分:0)

您应该考虑使用subscribe代替promise。 但是,如果您想使用promises,请将 booking.service.ts 文件更改为

getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .map(response => response.json().bookingDetails.data as Bookings[])
            .toPromise()
            .catch(this.handleError);
    }