要在Angular中获取JSON并将其作为Map使用,可以按照以下步骤:
data.service.ts
的服务文件:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
public getJSON(url: string): Observable
DataService
并在构造函数中注入该服务:import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
template: `{{ data | json }}`
})
export class AppComponent {
public data: Map;
constructor(private dataService: DataService) {
this.dataService.getJSON('assets/data.json').subscribe((result) => {
this.data = result;
});
}
}
assets
文件夹中创建一个名为data.json
的JSON文件,并将其填充为一个键值对的JSON对象,如下所示:{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
app.module.ts
中,导入HttpClientModule
并将其添加到imports
数组中: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 { }
这样,你就可以在Angular中获取JSON并将其作为Map使用了。在上面的示例中,将JSON数据绑定到了data
变量,并在模板中使用{{ data | json }}
来显示该数据。你可以根据需要修改代码来满足你的具体需求。
上一篇:Angular获取JSON数组