首页 > 解决方案 > 如何从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 中只是空的。任何指导将不胜感激,谢谢。

标签: javascriptangulartypescriptsubscribengoninit

解决方案


在您的代码中,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;
    });
}

推荐阅读