Search code examples
angularangular-material2angular-httpangular-httpclient

How to sort through HTTP GET Response to get one element at a time with Angular 5


This is my code for my DataService where I am mapping my Regions:

 import { Injectable, OnInit } from '@angular/core';
    import { HttpClient, HttpParams } from "@angular/common/http"
    import { Observable } from 'rxjs/Observable';
    import { Data } from '../models/data.model'
    import { Region } from '../models/region.model';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/switchMap';



    @Injectable()
    export class DataService {
      dukeProgress: string;
      dukeCarolinas: string;
      dukeFlorida: string;
      dukeMidWest: string;


      constructor(private httpClient: HttpClient,
      ) { }

     getRegion() {
        return this.httpClient.get('http://example.com/otdcc/v1/cc/regions').map(
          (region: Region[]) => {
            const regions = region
            for (const region of regions)
              return region;
          }
        );
      }
    }

This is my code in my component where I am subscribing:

  showRegions() {
    this.dataService.getRegion().subscribe(
      data => {
        console.log('this is the data:' + ' ' + data)
        this.dataSource = new MatTableDataSource<Opcenter[]>(<any>data);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      },
      err => {
        this.showSearchBox = true;
      }
    )
    this.showSearchBox = true;
  }

I want to be able to sort through the response I am getting back from my GET request and take out one object at a time from the response to use it in another function that requires the data I get back from the response(an HTTP post request), but I do not know how too. I've looked at examples, but I don't seem to get it. Can someone please break it down step by step? Or if not at least point me in the right direction? I know I have to use JSON.Parse and use it in an array, but I'm not sure if it'll be within where I subscribe to it? I'm not sure. Please help!


Solution

  • Observable represent asynchronous data streams or emits a sequence of items over time
    Http is a request-response protocol and it returns an observable but unlike the definition, it's doesn't emit values over time instead you make a request get a whole response it does not arrive in an asynchronous fashion and done The Observable never emits again unless you make a fresh request.

    HttpClient simplifies the default ergonomics (You don't need to map to json anymore) and now supports typed return values.

    getRegion():Observable<Region[]> {
            return this.httpClient.get<Region[]>('http://example.com/otdcc/v1/cc/regions')}
    

    Http returns an observable and We can tell the HttpClient.get to return response as Region type When we use http.get<Region[]>(...) then it returns the instance of Observable<Region[]> type.

    To pass one object at a time you can use forEach which executes a provided function once for each array element inside your subscribe call back which ensures that your method is invoked after your subscription is resolved.

    Modified Code

        showRegions() {
            this.dataService.getRegion().subscribe(
              data => {
                  data.forEach(value=>this.myMethod(value));
                console.log('this is the data:' + ' ' + data)
                this.dataSource = new MatTableDataSource<Opcenter[]>(<any>data);
                this.dataSource.paginator = this.paginator;
                this.dataSource.sort = this.sort;
              },
              err => {
                this.showSearchBox = true;
              }
            )
            this.showSearchBox = true;
          }
    
      myMethod(data:Region)
    {
       console.log(data);//your logic
    }
    

    Live Demo