【问题标题】:Fetching a json file in Angular 2 [duplicate]在Angular 2中获取json文件[重复]
【发布时间】:2023-03-13 06:00:01
【问题描述】:

关于 SO 的解决方案很少,但显然它们已被弃用。 Angular 2 一直在变化...

我正在尝试将 json 文件提取到我的文件中。

有一个items.json 文件。

我想知道我是否能够在一个文件中完成这项工作?我的意思是,就在app.component.ts 内? app.component.ts 文件实际上看起来像:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Injectable }     from '@angular/core';

@Component({
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


@Injectable()
export class AppServices{

  constructor(private http: Http) {
    let obj;
     this.getJSON().subscribe(data => obj=data, error => console.log(error));
  }

  public getJSON(): {
    return this.http.get("./items.json")
      .map((res:any) => res.json())
  }
}

export class AppComponent {
    let items = getJSON();
  }
}

或者也许我必须包含一个app.service.ts 文件?并把获取json的代码放在那里?在 Angular1 中很容易做到这一点,为什么他们把它搞得这么复杂......

我正在寻找可能的最短解决方案我会投票给每个答案。提前谢谢你

编辑 我得到了另一个代码:

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'watchlist',
  templateUrl: './watchlist.component.html',
  styleUrls: ['./watchlist.component.css']
})


export class WatchlistComponent {

  data;

  constructor(private http:Http) {
    this.http.get('items.json')
      .subscribe(res => this.data = res.json());
  }

}

如何将此数据加载到我的 items 变量中?

【问题讨论】:

  • “另一个代码”看起来不错。但是如果你键入'data'变量,它会更好

标签: javascript json angular


【解决方案1】:

// 一个函数你可以声明一个应用程序

app() {
    return this.http.get('/config.json');
  }

 this.app().subscribe((data: any) => {
 }

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多