如何在Angular 6 / RxJS 6中处理来自http.get()的结果?

时间:2018-05-04 17:11:05

标签: angular rxjs

我正在尝试将应用程序从Angular 5升级到Angular 6,并且无法弄清楚如何使用RxJS的新语法。这是我正在尝试迁移的代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class SearchService {
  constructor(private http: HttpClient) {}

  getAll() {
    return this.http.get('assets/data/people.json');
  }

  search(q: string): Observable<any> {
    if (!q || q === '*') {
      q = '';
    } else {
      q = q.toLowerCase();
    }
    return this.getAll().map((data: any) => {
      const results: any = [];
      data.map(item => {
        // check for item in localStorage
        if (localStorage['person' + item.id]) {
          item = JSON.parse(localStorage['person' + item.id]);
        }
        if (JSON.stringify(item).toLowerCase().includes(q)) {
          results.push(item);
        }
      });
      return results;
    });
  }

  get(id: number) {
    return this.getAll().map((all: any) => {
      if (localStorage['person' + id]) {
        return JSON.parse(localStorage['person' + id]);
      }
      return all.find(e => e.id === id);
    });
  }

  save(person: Person) {
    localStorage['person' + person.id] = JSON.stringify(person);
  }
}

我知道导入应该改为:

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

你现在应该使用pipe()而不是map(),但我在解决问题时遇到了问题。如果它像下面那样简单,那就太棒了,但它似乎并不是。

    return this.getAll().pipe(
      map(data: any) => {
        const results: any = [];
        data.map(item => {
          // check for item in localStorage
          if (localStorage['person' + item.id]) {
            item = JSON.parse(localStorage['person' + item.id]);
          }
          if (JSON.stringify(item).toLowerCase().includes(q)) {
            results.push(item);
          }
        });
        return results;
    }));

1 个答案:

答案 0 :(得分:5)

您在map(data:any) => {}错过了一个括号。这应该有效:

return this.getAll().pipe(
    map((data: any) => {
        const results: any = [];
        data.map(item => {
            // check for item in localStorage
            if (localStorage['person' + item.id]) {
                item = JSON.parse(localStorage['person' + item.id]);
            }
            if (JSON.stringify(item).toLowerCase().includes(q)) {
                results.push(item);
            }
        });
        return results;
    }
    )
);

你可以用这样一种更具可读性和功能性的方式来做 - 使用Array.prototype.map函数来实现它应该使用的东西并添加一个过滤器:

return this.getAll().pipe(
    map(
        data => data
             .map(item => !!localStorage['person' + item.id]
                ? JSON.parse(localStorage['person' + item.id])
                : item)
             .filter(item => JSON.stringify(item).toLowerCase().includes(q))
    )
);