以下是一个使用Angular 7从服务器获取JSON数据并存储在本地的示例解决方法:
data.service.ts
的服务文件,用于从服务器获取和存储数据:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'http://example.com/api/data'; // 替换为服务器API的URL
constructor(private http: HttpClient) { }
fetchData() {
return this.http.get(this.apiUrl);
}
saveData(data: any) {
// 在这里执行将数据保存到本地的逻辑
// 例如,可以使用localStorage或将数据存储到数据库等
}
}
DataService
并使用它来获取和存储数据。例如,创建一个名为home.component.ts
的组件:import { Component, OnInit } from '@angular/core';
import { DataService } from 'path/to/data.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
data: any; // 存储从服务器获取的数据
constructor(private dataService: DataService) { }
ngOnInit() {
this.getData();
}
getData() {
this.dataService.fetchData().subscribe((response: any) => {
this.data = response;
this.dataService.saveData(this.data); // 将数据保存到本地
});
}
}
home.component.html
中,使用data
变量来显示从服务器获取的数据:
Data from server:
{{ data | json }}
在这个示例中,DataService
服务用于从服务器获取数据并将其存储在组件中的data
变量中。然后,saveData()
方法被调用以将数据保存到本地。
请确保将path/to/data.service
替换为实际的data.service.ts
文件的路径。此外,还要替换http://example.com/api/data
为实际的服务器API的URL。