[英]Angular 8 Observable Returns “_isScalar:false…”
Just trying to simply display the contents of a JSON object from a GET request. 只是尝试简单地显示来自GET请求的JSON对象的内容。
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: 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: 我希望不必使用'keyvalue'管道,但这似乎是获得所有返回值的唯一方法,但是这是调用函数时返回的屏幕快照:
An observable can not be used as a value. 可观察值不能用作值。
You have to use the pipe async
to get the value of an observable. 您必须使用管道
async
来获取可观察值。
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: 您需要像这样在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.