只需尝试简单地显示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'管道,但这似乎是根本不返回任何东西的唯一方法,但是下面是该函数调用时返回的屏幕截图:
答案 0 :(得分:1)
不能将可观察值用作值。
您必须使用管道async
来获取可观察值。
答案 1 :(得分:0)
要获得一个干净的解决方案,最好创建一个返回服务的接口:
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
});
}