正确使用RxJS的方法

时间:2018-11-08 05:08:40

标签: angular rxjs6

我在Angular中有此方法(最新的package.json显示7.0.0)和Rxjs 6.3.3。我正在调用 SpringBoot Rest API,该API返回航班列表。我想转换为Observable<Flight[]>

search(searchquery): Observable<Flight[]>
  {
    return this.http.post('/searchservice/search/get', searchquery)
      .pipe(map(response => 
      {
        return (response.map((flight: Flight) =>
        {
          return new Flight().deserialize(flight);
        }));
      }));

  }

但是在构建时,出现此错误

  

“错误TS2339:类型“对象”上不存在属性“地图””

。错误显示在response.map((flight: Flight) =>代码中。我可以知道我做错了吗? 根据以下查询,这是打印的json响应。

0: {id: 4, flightNumber: "BF101", origin: "NYC", destination: "SFO", flightDate: "22-JAN-16", …}
1: {id: 7, flightNumber: "BF105", origin: "NYC", destination: "SFO", flightDate: "22-JAN-16", …}
2: {id: 10, flightNumber: "BF106", origin: "NYC", destination: "SFO", flightDate: "22-JAN-16", ..}

还有一件事。该代码昨天完美运行,但是今天早晨,它开始显示错误。奇怪的!!! 我试图做的事情类似于下面的代码,该代码写在《 Angular的完整书》一书中。

return this.http.get(queryUrl)
  .map((response: Response) => {
   return (<any>response.json()).items.map(item => {
   SearchResult({
      id: item.id.videoId,
      title: item.snippet.title,
      description: item.snippet.description,
      thumbnailUrl: item.snippet.thumbnails.high.url
    });
  });
});

1 个答案:

答案 0 :(得分:0)

最后,这是起作用的代码。将响应投射为<Flight[]>,然后将其映射。

search(searchquery): Observable<Flight[]>
  {
    return this.http.post('/searchservice/search/get', searchquery)
      .pipe(map(response =>
      {
        return (<Flight[]>response).map(flight => new Flight().deserialize(flight))
      }));

  }