繁体   English   中英

Angular 8 Observable返回“ _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'管道,但这似乎是获得所有返回值的唯一方法,但是这是调用函数时返回的屏幕快照:

在此处输入图片说明

可观察值不能用作值。

您必须使用管道async来获取可观察值。

为了获得一个干净的解决方案,最好创建一个返回服务的接口:

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

  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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