How can I process results from http.get() in Angular 6/RxJS 6?

Matt Raible

I'm trying to upgrade an application from Angular 5 to Angular 6 and having trouble figuring out how to use RxJS's new syntax. Here's the code I'm trying to migrate:

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);
  }
}

I know the imports should change to:

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

And you're supposed to use pipe() instead of map() now, but I'm having issues figuring out how. It'd be awesome if it was as simple as the following, but it doesn't seem to be.

    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;
    }));
funkizer

You're missing a parentheses at map(data:any) => {}. This should work:

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;
    }
    )
);

You could do it in a more readable and functional way like this - use the Array.prototype.map function for what it's supposed to be used and add a filter:

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))
    )
);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I save http get response object in angular 6

How I can get response from express with Angular 6

Angular 6 - using await for http client, how can I get status code if failed

Angular 6: how to get http at an interval

How do I get environmment process.NODE_ENV=development in server.ts in angular 6 universal

I dont get rxjs 6 with angular 6 with interval, switchMap, and map

HTTP get call in Angular 6

ANGULAR 6 http get JSON

How to get data from Iframe with Angular 6

How to return value from subscribe of forkJoin with angular 6 and RxJs 6?

Show object in input fields from http GET, Angular 6

How can I get the selected date from an Angular date picker and pass it to $http service parameter

How can I access an individual element from JSON file via Angular4 HTTP Get?

Can i migrate safety from angular 6 to angular 9?

How to get the results from "\033[6n" in an sh script

How can i get results from two MySql tables

How can i get the accurate results from sql query

How can I execute SQL and get results from PHP?

How can i get results from another Entity with conditions?

In AngularJS How can I get a total from filtered results?

How can i get the actual results from this code

How can I get return value from a spawned process in Erlang?

How can I get selected radio button id in angular6

Angular/RxJS 6: How to prevent duplicate HTTP requests?

How to make a sequence of http requests in Angular 6 using RxJS

How to get results with angular.js $http?

How to call Http post and get request in angular 6

Angular 6: given ElementRef, can I get ViewContainerRef

I can't get my angular 6 *ngIf statement to work

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive