Angular 8 个 Observable Returns“_isScalar:false...”

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

只是试图简单地显示来自 GET 请求的 JSON 对象的内容。

服务:

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

组件:

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>

我宁愿不必使用 'keyvalue' 管道,但它似乎是获得任何返回值的唯一方法,但这是调用函数时返回的内容的屏幕截图:

Observable 不能用作值。

您必须使用管道 async 来获取 observable 的值。

要有一个干净的解决方案,最好创建一个服务接口 return:

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

比在您的服务文件中:

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

您需要像这样在 AppComponent 中订阅您的可观察对象:

public lights: Lights;

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

  }