Home > database >  Angular: Printing returned object in html coming from api service
Angular: Printing returned object in html coming from api service

Time:09-01

I'm having trouble accessing the result of my get call to an api. The service returns a car object, after the user inputs his license plate in the input.

My service:

import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';


@Injectable({providedIn: 'root'})

export class KentekencheckService {
  private readonly apiUrl = "https://opendata.rdw.nl/resource/m9d7-ebf2.json";

  constructor(private http: HttpClient) { }

  // fetch Alle Kentekens
  getKentekens(kentekenvalue: string): Observable<any> {

    let params = new HttpParams()
    .set('kenteken', kentekenvalue)
    return this.http
    .get<any>(this.apiUrl, {params});
  }

}

My Component.ts

import { Component, OnInit } from '@angular/core';
import { KentekencheckService } from 'src/app/services/kentekencheck.service';

@Component({
  selector: 'app-stap1',
  templateUrl: './stap1.component.html',
  styleUrls: ['../steps.component.css']
})
export class Stap1Component implements OnInit {
  kentekenvalue: string = '';
  results: any = [];
  merk: string = '';
  handelsbenaming: string = ''

  constructor(private kentekencheckservice: KentekencheckService) { 

  }

onEnter() {
    this.kentekencheckservice.getKentekens(this.kentekenvalue).subscribe(
      (results:any) => {
        console.log(results);
      }
    );
}

  ngOnInit(): void { }
}

My Component.html:

 <div >
            <input type="text" placeholder="AA-123-B" id="kentekenInput" name="kentekenvalue" [(ngModel)]="kentekenvalue" (keyup.enter)="onEnter()">
            <ul *ngFor="result of results">
                <li>{{result.merk}}</li>
                <li>{{result.handelsbenaming}}</li>
            </ul>
            <button  routerLink="../stap2">Volgende</button>
        </div>

The console is logging the right object:

console log

After extensive searching I am assuming the problem is it's returning an object in stead of an array I can iterate over. Could you help me out how to print the returned value (for example the 'merk' of the object: "OPEL")?

Thanks in advance

CodePudding user response:

You in fact do have an array as you can see from the length of 1.

The issue is you never assign your return value.

 this.kentekencheckservice.getKentekens(this.kentekenvalue).subscribe(
  (results:any) => {
    console.log(results);
  }
);

only outputs the return. In order to assign you must do:

 this.kentekencheckservice.getKentekens(this.kentekenvalue).subscribe(
  (results:any) => {
    this.results = results;
    console.log(this.results);
  }
);

Also, how are you even seeing console.log from onEnter? It does not appear to be called anywhere.

  • Related