【发布时间】: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