简体   繁体   English

Angular 2从url获取json数据

[英]Angular 2 get json data from url

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let ep = './data.json';
this.events = this.http
  .get(ep, { headers: headers })
  .map(res => res.json())
  .map(({results}: { results: Data[] }) => {
    return results.map((data: Data) => {
      return {
        title: data.title,
        start: new Date(data.from),
        colors.yellow,
      };
    });
  });

Here is my code in Angular 2. I want to get data from a JSON file and show it in the angular-calendar. 这是我在Angular 2中的代码。我想从JSON文件中获取数据并在angular-calendar中显示它。 Here is angular-calendar Demo : How can I do that? 这是角度日历演示 :我怎么能这样做?

You can make a service that contains the data for the calendar. 您可以创建包含日历数据的服务。

getList(): any
{

var date = new Date( '2017-01-12' );
var date2 = new Date( '2017-03-17' );

return (
  [

    { title: 'Beauty And The Beast', start: date2, color: { primary: '#e3bc08', secondary: '#FDF1BA' } },

    { title: 'La La Land', start: date, color: { primary: '#e3bc08', secondary: '#FDF1BA' } }

  ]
)
}

Then you will have to remove the async pipe from the template. 然后,您必须从模板中删除异步管道。

Before: 之前:

[events]="(events | async ) || []

After: 后:

[events]="(events) || []

Then call the service in the component: 然后调用组件中的服务:

fetchEvents()
{

this.events= this._data_Service.getList()

}

2 . 2 To get data.json file with Http you need to put the JSON file in the assets folder: ./assets/data.jsom , so that it can be accessed by the application: localhost:8080/data.json . 要使用Http获取data.json文件,您需要将JSON文件放在assets文件夹: ./assets/data.jsom localhost:8080/data.json ,以便应用程序可以访问它: localhost:8080/data.json

Then you simply make a get request. 然后你只需要一个get请求。

fetchEvents(): void {


    this.events = this.http
      .get('../../assets/data.json') // the path may vary depending 
                                    // on your directory structure. 
      .map(res => res.json())
      .map((results) => {  // this might be different depending on
                          //  your json and type definition.

        return results.map((data: Data) => {

          console.log({title: data.title,
            start: new Date(data.from),
            color: colors.yellow})

          return {
            title: data.title,
            start: new Date(data.from), 
            color: colors.yellow,data
          };
        });
      });


}// fetchEvents

Here is the JSON I used: 这是我使用的JSON:

[

{"title":"La La Land","from":1490475722305},
{"title":"Beauty And The Beast","from":1490475722305}

]

finally, you can include the type definition in your component: 最后,您可以在组件中包含类型定义:

interface Data {

  title: string;
  from:string;

}

interface DataEvent extends CalendarEvent {
  data: Data;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM