简体   繁体   中英

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:

在此处输入图片说明

An observable can not be used as a value.

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

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
  });

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM