Ionic 4 Sorting data from api call

I’m trying to sort the data I get from my api call into two seperate lists, but I’m struggling to pipe the data from the call.

rest-api.service.ts


getVessels(): Observable<string[]> {
  let response = this.http.get(apiUrl+'/api/orders/GetVesselOrders?VesselID=5055');
  return this.http.get('https://navfleet.azurewebsites.net/api/orders/GetVesselOrders?VesselID=5055', {headers : new HttpHeaders({'Authorization':'Bearer ' + localStorage.getItem('userToken')})})
  .pipe(
    map(this.extractData),
    catchError(this.handleError)
  );
  
  }

private extractData(res: Response) {
  let body = res;
  return body || {};
}

private handleError (error: Response | any) {
  let errMsg: string;
  if (error instanceof Response) {
    const err = error || '';
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  console.error(errMsg);
  return Observable.throw(errMsg);
}

Type ‘Observable<{}>’ is not assignable to type ‘Observable<string>’. Type ‘{}’ is missing the following properties from type ‘string’: length, pop, push, concat, and 26 more.ts(2322)
(property) RestApiService.http: HttpClient

Is the error I’m receiving on the return line of the function getVessels()

List.ts

  
import { Component, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ActionSheetController, ModalController } from '@ionic/angular';
import { NotificationPage } from '../notification/notification.page';
import { LoadingController } from '@ionic/angular';
import { RestApiService, Vessel } from '../../services/API/rest-api.service';
import { a, b } from '@angular/core/src/render3';

@Component({
  selector: 'page-order-list',
  templateUrl: 'order-list.html',
  styleUrls: ['./order-list.scss'],
  encapsulation: ViewEncapsulation.None
})
export class OrderListPage {
  excludeTracks: any = [];
  searchTerm: string = '';
  Vessel: any;
  data1: any;
  filter: any;
  vessels: string[];
  errorMessage: string;

  constructor(
    public router: Router,
    public modalCtrl: ModalController,
    public api: RestApiService,
    public loadingController: LoadingController,
    public restApiService: RestApiService
    

  ) { }
  
  ngOnInit() {
    this.getData();
    console.log(this.api.getVessels);

  }

  async getData() {
    const loading = await this.loadingController.create({
      message: 'Loading'
    });
    await loading.present();
    this.api.getVessels()
      .subscribe(vessel => {
        console.log(vessel);
        this.Vessel = vessel;
        this.filter = vessel;
        error =>  this.errorMessage = <any>error;
        loading.dismiss();
      }, err => {
        console.log(err);
        loading.dismiss();
      
      });
  }

If i change Observable in the getVessels() function where i call the api data to “Observable” I get no syntax errors but my data won’t load.

HTML

 <ion-item style="color:#595b60; font-weight: bold;" *ngFor="let vessels of vessel">
  
          <ion-label class="order">{{vessels.VesselName}}</ion-label>
          <ion-label class="dateTime"><p class="p">{{vessels.Date}}</p></ion-label> 
          <ion-label class="product"><p class="p">{{vessels.NumberOfProduct}} Products</p></ion-label>
          <ion-label class="cost"><p class="p">{{vessels.TotalAmount}} USD</p></ion-label>  
          <ion-img class="icon" src="../../assets/img/filled-circle.png"></ion-img>
          <ion-img class="icon1" src="../../assets/img/filled-circle.png"></ion-img>

          <ion-icon slot="end" name="ios-arrow-forward"></ion-icon>
      </ion-item>        
    </ion-item-group>

Any idea what I’m doing wrong?

Also haven’t Applied the pipe to *ngFor=“let vessels of vessel” line since the data won’t show.

I am able to print one line of the data array called from the api by updating the getData function to this

 async getData() {
    const loading = await this.loadingController.create({
      message: 'Loading'
    });
    await loading.present();
    this.api.getVessels()
      .subscribe(res => {
        console.log(res);
        this.Vessel = res[0];
        this.filter = res[25];
        loading.dismiss();
      }, err => {
        console.log(err);
        loading.dismiss();
      });
  }

How can i make " this.Vessel = res[0];" not only show the [0] line of the data array but show all my 29 lines

Your error message suggests you’re using HttpClient (which is good) but interacting with it as if it were old Http (which is bad). Please follow the idioms in here and get rid of every single instance of any in your code.

Managed to make the Data show, now I’m trying to apply a pipe to sort the data.

Pipes are a bad choice for that, for reasons explained here.

I’ll try sorting them with an If and Else If statement then.



  getStatus() {
    this.restApiService.getVessels().subscribe((data : any)=>{
      this.vessels = data;
      
      this.vessels.forEach((vessel: any, vesselApproved: any, vesselNotProcessed: any) => {
        if(vessel.Status == "Approved") {

        }else if (vessel.Status == "NotProcessed") {

        }

      
          console.log(vessel.VesselName);
      });

    });

  }     
  

Managed to solve my issue creating two functions separating the data from the API call

 getNotProcessed() {
    this.restApiService.getVessels().subscribe((data : any)=>{
      this.notProcessed = data.filter(entry => entry.Status === "NotProcessed") 
    });

  }
  
  getApproved () {
    this.restApiService.getVessels().subscribe((data : any)=>{
      this.approved = data.filter(entry => entry.Status === "Approved") 
    });

  }
  

One additional modification you might consider is to move both of these functions up into restApiService. At that point, it would be easy for them to share a common call to getVessels() if that might improve your performance and bandwidth usage.

Ohh really? I’ll be sure to do that, thank you for the help!