我现在将以前的名称更改为当前名称。任何帮助或想法都非常有用!提供了json文件,因此我实际上并没有使用任何东西,它仍然可以工作
注意:我不确定是否需要创建服务文件。
这是我的代码:
app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public countries: any;
public displayedColumns: string[] = ['Code', 'Name'];
constructor
(
public httpClient: HttpClient
)
{
}
应用模块。 ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app组件html
<div style="text-align:left;width:500px;">
<h1>
Tables with data
</h1>
<table *ngIf="countries">
<!-- ADD HEADERS -->
<tr>
<th>c</th>
<th>N</th>
<th>C</th>
</tr>
<!-- BIND ARRAY TO TABLE -->
<tr">
<td>{{c}}</td>
<td>{{n}}</td>
<td>{{C}}</td>
</tr>
</table>
</div>
答案 0 :(得分:2)
问题是您的json
文件是一个Country
属性的对象,但是您的代码希望接收一个数组。
因此,您可以将json
文件重新格式化为一系列国家/地区...
请注意,我还使用界面而不是countries
键入了您的any
属性,并在httpClient.get<T>
模板化方法中指定了类型。
此处提供的StackBlitz示例适用于以下代码:https://stackblitz.com/edit/angular-stackoverflow-52895400
StackBlitz替代示例,如果您想处理json文件中的多个属性:https://stackblitz.com/edit/angular-stackoverflow-52895400-alt
countries.json
[
{
"Code": "ALB",
"Name": "Albania",
"Continent": "Europe"
},
{
"Code": "ARG",
"Name": "Argentina",
"Continent": "South America"
},
{
"Code": "BEL",
"Name": "Belgium",
"Continent": "Europe"
}
]
app.component.ts
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
export interface Country {
Code: string;
Name: string;
Continent: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public countries: Country[];
constructor(
public httpClient: HttpClient
) { }
ngOnInit() {
this.httpClient.get<Country[]>('../assets/data/countries.json').subscribe(
countries => {
this.countries = countries;
console.log(this.countries);
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}
}