可能只是我,但我在使用Angular文档的时候真的很糟糕。例如,我试图理解如何阅读(在其上运行循环并从应用程序中提取一些数据)JSON文件,我发现了Angular文档的这个链接:https://angular.io/guide/http
他们会发布以下代码,但不要说它应该去哪里(到哪个文件):
@Component(...)
export class MyComponent implements OnInit {
results: string[];
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
// Make the HTTP request:
this.http.get('/api/items').subscribe(data => {
// Read the result field from the JSON response.
this.results = data['results'];
});
}
}
附注:我将我的JSON文件放在assets文件夹中,我想在几个组件中使用它的数据。
附注二:我非常感谢您对如何处理文档的帮助,也许我错过了什么?新手很难理解究竟发生了什么。
由于
答案 0 :(得分:0)
// version without map
@Component(...)
export class MyComponent implements OnInit {
results: string[];
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
// Make the HTTP request: Add **.json** if it's a json file
this.http.get('/api/items.json').subscribe(data => {
// Read the result field from the JSON response.
this.results = data['results'];
});
}
}
// with map
import 'rxjs/add/operator/map'
@Component(...)
export class MyComponent implements OnInit {
results: string[];
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
// Make the HTTP request:
this.http.get('/api/items.json')
.map((data) => {
return data.json();
})
.subscribe((data) => {
this.results = data['results'];
});
}
}