我正在调用一个返回
JSON对象的API.我只需要将数组的值映射到Observable.如果我调用api只返回数组我的服务调用工作.
以下是我的示例代码..
// my service call .. import { Injectable } from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {Show} from '../models/show'; import {HttpClient} from '@angular/common/http'; @Injectable() export class MyService { constructor(private http: HttpClient ) { } findAllShows(): Observable<Show[]> { return this.http .get<Show[]>(`${someURL}/shows`) } }
如果返回是一个JSON对象,如下面这个失败..
// Service API that FAILS ... { "shows": [ { "id": "123f9165-80a2-41d8-997a-aecc0bfb2e22","modified": "2017-08-13 15:54:47","name": "Main Show1" },{ "id": "456f9165-80a2-41d8-997a-aecc0bfb2e22","modified": "2017-08-14 15:54:47","name": "Main Show2" },{ "id": "789f9165-80a2-41d8-997a-aecc0bfb2e22","modified": "2017-08-17 15:54:47","name": "Main Show3" } ] }
现在这个可以工作,如果我只是返回数组
// Service API that Works ... [ { "id": "123f9165-80a2-41d8-997a-aecc0bfb2e22",{ "id": "789f9165-80a2-41d8-997a-aecc0bfb2e22","name": "Main Show3" } ]
如何将JSON对象Observable映射到数组Observable ???
你可以简单地.map()你的http调用,它是一个Observable,来返回你想要的数据类型.
原文链接:https://www.f2er.com/angularjs/141997.htmlfindAllShows(): Observable<Show[]> { return this.http .get(`${someURL}/shows`) .map(result=>result.shows) }
你的httpClient.get()应该返回一个Observable,你已经明确表示它认为Observable< Show []>.你.map()是一个将observable转换为新的observable的运算符.
有关.map()运算符的更多信息:http://reactivex.io/documentation/operators/map.html