javascript - 如何从Angular中的http / async调用为接口属性赋值?
问题描述
我有一个返回 JSON 对象的服务,我想将此数据分配给接口属性。这是下面的代码,这里的 component.ts 代码已被剥离,只包含相关部分。
服务.ts 文件
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private httpClient: HttpClient) { }
public getFanSpeed(){
return this.httpClient.get('http://localhost:4000/auth/get-fan-speed');
}
}
组件.ts 文件
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../api.service';
interface CardSettings {
content: string;
}
@Component({...})
export class DashboardComponent implements OnInit {
fanSpeed: string;
ngOnInit() {
this.apiService.getFanSpeed().subscribe((response)=>{
this.fanSpeed = response['fanSpeedVar'];
});
}
fanSpeedCard: CardSettings = {
content: this.fanSpeed
};
constructor(private apiService: ApiService) {}
}
我在 ngOnInit() 函数中放置了一个 console.log,我可以看到正确的值,但由于某种原因,它没有正确分配给接口属性,因此在 UI 中只是空的。任何指导将不胜感激,谢谢。
解决方案
在您的代码中,fanSpeedCard 是一个属性,它在您的类(DashboardComponent)构造时分配了对象的值(带有 CardSettings 接口) :
fanSpeedCard: CardSettings = {
content: this.fanSpeed
};
由于 fanSpeed 最初没有定义(仅作为字符串类型)并且由于您没有在 API 响应中更新 CardSettings 对象 - 您的 UI 不会更改。
如评论中所述,您需要确保更新订阅块内的 CardSettings 内容属性的值(不仅仅是 fanSpeed):
gOnInit() {
this.apiService.getFanSpeed().subscribe((response)=>{
this.fanSpeed = response['fanSpeedVar'];
this.fanSpeedCard.content = this.fanSpeed;
});
}
推荐阅读
- angular - chartjs 角度更新顺序
- android-jetpack-compose - Jetpack 是否为 LazyColumnFor/LAazyRowFor 发布 onClickListener?
- bootstrap-4 - 引导表单验证仅在重新加载页面后在 nuxt.js 中有效
- maven - Gitlab maven 部署到包注册表
- python - AWS API 网关 Datestamp 不是 JSON 可序列化的
- terraform - CodeDeploy 命令与 terraform 状态混淆
- python - 在数据流入 GCP 时迭代存储桶内容
- reactjs - 我如何只希望单击的项目出现在模式上?
- python - Python 对 CSV 的请求
- java - Spring Boot 可运行 jar 中的 ANT 类路径