gpt4 book ai didi

javascript - Angular 6 HTTPClient 和 Observable

转载 作者:行者123 更新时间:2023-11-30 20:16:39 26 4
gpt4 key购买 nike

我正在尝试从 HTTP 端点加载以下结构:

{
"dbHeartbeats": [
[
{
"size": [
"2113464 documents"
],
"buildInfo": [
"4.0.0"
],
"heartbeat": [
true
],
"name": [
"MongoDB"
]
},
{
"size": [
"8549 kB"
],
"buildInfo": [
"PostgreSQL 10.4 (Debian 10.4-2.pgdg90+1)"
],
"heartbeat": [
true
],
"name": [
"PostgreSQL Database"
]
}
]
]

所以我写了两个接口(interface):

export interface DbHeartbeats {
name: string;
}

import { DbHeartbeats } from "./db-heartbeats";

export interface Heartbeats {
dbHeartbeats: DbHeartbeats;
}

调用端点并返回可观察值的简单服务:

import { Injectable } from '@angular/core';
import { Heartbeats } from './heartbeats';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';


@Injectable({
providedIn: 'root'
})
export class HeartbeatService {
heartbeats$: Observable<Heartbeats>;
apiRoot = 'http://localhost:9090/backend/rest/v1/heartbeat';

constructor(private httpClient: HttpClient) {
this.heartbeats$ = this.getHeartbeats();
}
getHeartbeats() {
return this.httpClient.get<Heartbeats>(this.apiRoot);
}
}

和一个模板

<div style="text-align:center">
<div *ngFor="let item of (heartbeatService.heartbeats$ | async).dbHeartbeats">
Test {{item.name}}
</div>
</div>

import {Component} from '@angular/core';
import {HeartbeatService} from './heartbeat.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

constructor(public heartbeatService: HeartbeatService) {
}
}

但我总是收到错误消息“无法读取 null 的属性‘dbHeartbeats’”。这让我发疯,我不明白我在这里做错了什么。有什么建议吗?

最佳答案

根据您提供的数据样本,您应该像这样定义您的接口(interface):

export interface DbHeartbeats {
size: string;
buildInfo: string;
heartbeat: boolean;
name: string;
}

export interface Heartbeats {
dbHeartbeats: Array<DbHeartbeats>;
}

然后是你的getHeartbeats函数将返回 Observable<Heartbeats>你期待的。

关于javascript - Angular 6 HTTPClient 和 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com