-4

I am trying to call my API with Angular 8 and log the JSON response into the console, but no matter what I do, the console says something is undefined and not logging anything else.

Component:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpdaService } from '../httpda.service';
import { Kbs } from '../kbs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  observableKbs: Observable<any[]>;
  kbs: Kbs[];

  constructor(private http: HttpdaService) { }

  ngOnInit() {
    this.getKbs();
    console.log(this.kbs);
  }

  getKbs() {
    this.observableKbs = this.http.getKbs();
    this.observableKbs.subscribe(
      kbs => this.kbs = kbs,
      err => this.http.checkErr(err)
    );
    return this.kbs;
  }
}

Service:

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

@Injectable({
  providedIn: 'root'
})
export class HttpdaService {
  serverUrl = 'http://127.0.0.1/';

  constructor(private http: HttpClient, private _router: Router) { }

  getKbs(): Observable<any> {
    return this.http.get<any>(this.serverUrl);
  }

  checkErr(err) {
    if (err instanceof HttpErrorResponse) {
        console.log(err.status);
    }
}

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

Model:

export class Kbs {
    'message': string;
}

What receive when I call my API with cURL -

curl 127.0.0.1 

{   "message": "welcome" }

This is what I get in the console -

enter image description here

Vignesh SP
  • 451
  • 6
  • 15

4 Answers4

0

The function in your service being an async method, returns value not as synchronously as you've predicted. The problems lie in the place you have given the log. The console.log(this.kbs) commands execute right after calling the this.getKbs() call not after the value is returned. This is why you are probably getting the value as undefined when you try to log it.
Try putting the log inside the function if you are just logging it. Or just try,

console.log(this.getKbs());

instead of

console.log(this.kbs);
0

You have an asynchronous call inside getKbs function. If you want to console the data you should move your console log inside the subscription like this:

    import { Component, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    import { HttpdaService } from '../httpda.service';
    import { Kbs } from '../kbs';

    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
      observableKbs: Observable<any[]>;
      kbs: Kbs[];

      constructor(private http: HttpdaService) { }

      ngOnInit() {
        this.getKbs();
      }

      getKbs() {
        this.observableKbs = this.http.getKbs();
        this.observableKbs.subscribe(
          kbs => {
             this.kbs = kbs,
             console.log(this.kbs);
          }
          err => this.http.checkErr(err)
        );
      }
    }

And in your code you returned undefined in getKbs function. Now you can use this.kbs instead of calling the getKbs function.

0

You do not subscribe kbs outside of scope, where you get data. if you need async data anywhere in your project, you have to subscribe again.

Also, if you use your async data in your template, use async pipe.

-2

It's very obvious what you're doing wrong.

kbs is undefined. On init you console log kbs. That's it. Your data gets set later on. Read about asynchronous functions.

Try logging when you actually set the data:

this.observableKbs.subscribe(
      kbs => {this.kbs = kbs; console.log(kbs)},
      err => this.http.checkErr(err)
    );
Carsten
  • 4,005
  • 21
  • 28