Joe Berthelot
Joe Berthelot

Reputation: 735

Angular 8 Observable Returns "_isScalar:false..."

Just trying to simply display the contents of a JSON object from a GET request.

Service:

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

@Injectable()
export class LightsService {

  constructor(private http: HttpClient) {}

  fetchLights(): Observable<Object> {
    const URL = 'http://****/api/S97t-zlmOCIeKXxQzU66WxWLY2z6oKenpLM95Uvt/lights';
    console.log('Service');
    return this.http.get(URL);
  }
}

Component:

import { Component } from '@angular/core';
import { LightsService } from './lights.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  lights;
  constructor(private lightsService: LightsService) {}

  fetchLights() {
    console.log('Component');
    this.lights = this.lightsService.fetchLights();
    console.log(this.lights);
  }
}

HTML:

<button (click)="fetchLights()">Fetch Lights</button>

<ul>
  <li *ngFor="let light of lights | keyvalue">{{light.key}}:{{light.value}}</li>
</ul>

I'd prefer to not have to use the 'keyvalue' pipe but it seems to be the only way to get anything returned at all, however here is a screenshot of what gets returned when the function is called:

enter image description here

Upvotes: 1

Views: 3671

Answers (2)

fedexo
fedexo

Reputation: 62

To have a clean solution, it's better to create an Interface of what service return:

interface Lights{
    label1: string;
    label2: string;
    ect ect
}

Than in your service file:

fetchLights(): Observable<Lights> {
    const URL = 'http://****/api/S97t-zlmOCIeKXxQzU66WxWLY2z6oKenpLM95Uvt/lights';
    console.log('Service');
    return this.http.get<Lights>(URL);
  }

You need to subscribe your observable in AppComponent like this:

public lights: Lights;

fetchLights() {
    console.log('Component');
   this.lightsService.fetchLights().subscribe((lights: Lights) => {
   this.lights = lights
  });

  }

Upvotes: 0

Gilsdav
Gilsdav

Reputation: 1155

An observable can not be used as a value.

You have to use the pipe async to get the value of an observable.

Upvotes: 2

Related Questions