从Angular中的服务器导入JSON

时间:2019-05-29 12:52:40

标签: json angular

我正在从JSON读取数据,JSON是服务器,它会定期更新和更改。我需要能够从服务器读取此JSON,以便在网页上显示最新信息。

当前,要能够读取它们存储在与我的有角项目相同的项目文件夹中的JSON。 (这是因为我启动时未在服务器上设置它们。)

这是我当前导入JSON以便能够读取的方式:

import jsonInfo from '../../../info.json'

我认为我可以将文件链接更改为服务器地址,如下所示:

import jsonInfo from 'http://servername/folder/info.json'

但是,VSCode给我一个错误:Cannot find module 'http://servername/folder/info.json'

这绝对是我要加载的JSON的位置,因为当我单击链接时,它将带我到JSON并显示它。

我的问题是,如何从服务器将JSON导入到.ts中,以便可以不断从JSON获取更新的信息?

3 个答案:

答案 0 :(得分:2)

服务器上的JSON文件与您尝试访问的任何其他Web资源(例如,API端点)一样。

因此,您应该使用内置的http客户端访问此JSON文件。

例如:

import { HttpClient } from '@angular/common/http';

export class SomeService {
  constructor(private http: HttpClient) { }

  getInfo() {
    return this.http.get('http://servername/folder/info.json');
  }

}


//...

export class SomeComponent implements OnInit {

  info: any;

  constructor(private someService: SomeService) {}

  ngOnInit() {
    this.someService.getInfo().subscribe(info => this.info = info)
  }

}

答案 1 :(得分:1)

使用HttpClient get方法。

this.httpClient.get('http://servername/folder/info.json').subscribe(data => { 
  // your logic
})

答案 2 :(得分:1)

您可以使用HttpClient并按如下所示进行操作

Working Demo

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {

  name = 'Angular';
  data = [];

  apiUrl = 'http://servername/folder/info.json';

  GetData() {
    this.http.get<any[]>(this.apiUrl)
      .subscribe(data => {
        this.data = data;
      });
  }

  ClearData() {
    this.data = [];
  }

  constructor(private http: HttpClient) {}
  ngOnInit() {}

}