【问题标题】:how to display data in front end in Angular如何在Angular的前端显示数据
【发布时间】:2021-01-01 18:28:10
【问题描述】:

我的数据库中有数据,并且我已经实现了后端 API 服务。我正在尝试在前端显示数据并进行渲染,但我不确定它为什么不显示。 任何建议或帮助将不胜感激。

我的后端 Get 方法之一

@Controller('helpSection')

export class HelpSectionController {
    constructor(private readonly helpSectionService: HelpSectionService) {}

    @Get()
    getHelpSection():Promise<HelpSectionEntity[]>{
        return this.helpSectionService.getHelpSection();
    }

我的前端 HTTP 获取之一

  constructor(private http: HttpClient) { }

  getHelpSection() {
    return this.http.get<HelpSection[]>(`${environment.api.chart}/helpSection`).pipe(first());
  }

只是为了测试,我在我的组件中这样做了

TS

import {HelpService} from '../../core/services/help.service'

  constructor(private HelpService: HelpService) {}

  helpSection$ = this.HelpService.getHelpSection();

  ngOnInit(): void {
    this.HelpService.getHelpSection().subscribe(() => {
    } )
  }

HTML

 {{helpSection$ | async}} // this display just [object Object]

<div *ngFor= "let help in helpSection$ | async">{{help.sectionName}}</div> // This is not showing anything

【问题讨论】:

  • 这说明你的前端绑定错误。您会看到 json 键值对的 object, object。绑定应该拼出键名。

标签: angular typescript api backend nestjs


【解决方案1】:
{{helpSection$ | async}} // this display just [object Object]

为此,数据已作为对象数组返回,因此您必须使用对象的键绑定它才能看到值。

<div *ngFor= "let help in helpSection$ | async">{{help.sectionName}}</div> // This is 
not showing anything

为此,请使用“of”而不是“in”:"let help of helpSection$"。当使用“of”时,“帮助”将是数组的成员,而在使用“in”时只是该成员的索引(意味着您必须使用 {{helpSection$[help].sectionName}})。

【讨论】:

    【解决方案2】:

    您的服务正在返回您 HelpSection[] ,我假设从那里开始

    return this.http.get<HelpSection[]>(`${environment.api.chart}/helpSection`).pipe(first());
    

    所以你有一个帮助部分模型,你为什么不稍后使用它?

    TS

    import {HelpService} from '../../core/services/help.service'
    
    import {HelpSection} from '../../..' //import it from where it is.
    
      constructor(private HelpService: HelpService) {}
    
      helpSection$ = this.HelpService.getHelpSection();
      helpSections : HelpSection[]
      ngOnInit(): void {
        this.HelpService.getHelpSection().subscribe( (data:HelpSection[]) => this.helpSections = data )
      }
    

    HTML

    <div *ngFor= "let help in helpSections">{{help.sectionName}}</div>
    

    注意:

    1)如果你想让它在 HTML 中可用,你的 HelpSection 模型必须有 id 和部分名称(如你的 json)

    2)在 HelpSection 中确保给出与 html 相同的大小写(在 ngfor {{}} 中)[helpSection/helpsection]

    3)你看,我不再使用异步了,如果你尝试我的风格,你不需要异步管道 HTML,但是如果你来自可观察但不仅仅是像我这样的数组,那么你必须使用异步管道HTML

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 2017-12-22
      • 2018-11-26
      • 2022-09-26
      • 2019-09-30
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多