【问题标题】:Making template display data on load在加载时制作模板显示数据
【发布时间】:2022-01-10 22:01:43
【问题描述】:

我试图让我的模板在加载时显示组件中的数据。我已经尝试将 *ngIf 条件设置为本身正在加载的对象。

像这样:

<table>
    <tbody *ngIf="country">
        <tr>
            <td>{{country.name}}</td>
            <td>{{country.population}}</td>
            <td>{{country.area}}</td>
            <td>{{country.language}}</td>
        </tr>
    </tbody>
</table>

但是,页面上没有显示任何内容。 这是我的组件的样子:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BackendService } from 'src/app/backend.service';
import { ICountry } from '../interfaces/country';

@Component({
  selector: 'app-countrydetails',
  templateUrl: './countrydetails.component.html',
  styleUrls: ['./countrydetails.component.css']
})
export class CountrydetailsComponent implements OnInit {

  public country: ICountry;

  constructor(private _backendService: BackendService, private router: Router) { }

  ngOnInit(): void {
    this.getCountry(this.router.url.replace('/',''));
  }

  getCountry(country: string): void {
    this._backendService.getCountry(country).subscribe(data => {
      this.country = data;
      console.log(data);
    });
  }
}

当对象不再未定义时,我应该怎么做才能让模板显示我的数据?

{{国家|json}}

{ "country": { "name": "Russia", "capital": "Moscow", "language": "Russian", "population": "144526636", "density": "8.4", "area": "3969100", "majorCities": [ { "name": "Moscow", "population": "12506468", "area": "2562", "rank": "1" }, { "name": "Saint Petersburg", "population": "5351935", "area": "1439", "rank": "2" }, { "name": "Novosibirsk", "population": "1473754", "area": "503", "rank": "3" } ] } }

【问题讨论】:

  • console.log(data) 是否显示从getCountry() 服务调用返回的数据?
  • 是的,它返回对象。
  • 如果您添加 {{country | json}} 在模板中的表格之外,会出现吗?
  • @Edward 是的,然后它确实出现了。
  • 您的table 标签在哪里?它是在父组件中定义的还是故意从您的模板中丢失的?

标签: javascript node.js angular


【解决方案1】:

您应该在 country 中存储您的 BackendService 的 observable。

public country: Observable<ICountry>;

ngOnInit() {
  this.country = this.getCountry(...);
}

getCountry(country: String): Observable<ICountry> {
  return this._backendService.getCountry(country);
}

然后,在您的 HTML 组件中

<tbody *ngIf="country | async as country">
    <tr>
        <td>{{country.name}}</td>
        <td>{{country.population}}</td>
        <td>{{country.area}}</td>
        <td>{{country.language}}</td>
    </tr>
</tbody>

【讨论】:

  • 我仍然遇到同样的问题,即页面上没有呈现任何内容。但是,正在绘制 tbody 和 tds。
  • 这个答案对解决 OP 问题没有任何作用。只是订阅 observable 的一种不同方式
猜你喜欢
  • 1970-01-01
  • 2018-08-19
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
相关资源
最近更新 更多