Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angular 2中获取JSON文件_Json_Angular - Fatal编程技术网

如何在Angular 2中获取JSON文件

如何在Angular 2中获取JSON文件,json,angular,Json,Angular,由于我是Angular的新手,任何人都可以给出一个使用Angular 2加载JSON文件数据的简单解决方案 我的代码如下 Index.html 角度2快速入门 System.import('app').catch(函数(err){console.error(err);}); 加载。。。 您需要对games.json进行HTTP调用以检索它。 比如: this.http.get(./app/resources/games.json).map 以下是我解析JSON的部分代码,可能对您有所帮助:

由于我是Angular的新手,任何人都可以给出一个使用Angular 2加载JSON文件数据的简单解决方案

我的代码如下

Index.html


角度2快速入门
System.import('app').catch(函数(err){console.error(err);});
加载。。。
您需要对
games.json进行HTTP调用以检索它。
比如:

this.http.get(./app/resources/games.json).map

以下是我解析JSON的部分代码,可能对您有所帮助:

import { Component, Input } from '@angular/core';
import { Injectable }     from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class AppServices{

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

    public getJSON(): Observable<any> {
         return this.http.get("./file.json")
                         .map((res:any) => res.json())
                         .catch((error:any) => console.log(error));

     }
}
从'@angular/core'导入{Component,Input};
从“@angular/core”导入{Injectable};
从'@angular/Http'导入{Http,Response,Headers,RequestOptions};
从'rxjs/Rx'导入{Observable};
导入'rxjs/add/operator/map';
导入“rxjs/add/operator/catch”;
@可注射()
导出类应用程序服务{
构造函数(专用http:http){
var-obj;
this.getJSON().subscribe(data=>obj=data,error=>console.log(error));
}
public getJSON():可观察{
返回此.http.get(“./file.json”)
.map((res:any)=>res.json())
.catch((错误:any)=>console.log(错误));
}
}

将json文件保存在Assets(与app dir并行)目录中

return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}
请注意,如果您使用ng new YourAppname生成,则此资产目录与“app”目录存在同一行,并且服务应该是app目录的子目录。可能如下所示:

::app/services/myservice.ts

getOrderSummary(): Observable {
    // get users from api
    return this.http.get('assets/ordersummary.json')//, options)
        .map((response: Response) => {
            console.log("mock data" + response.json());
            return response.json();
        }
    )
    .catch(this.handleError);
} 

如果使用angular cli,请将json文件保存在Assets文件夹(与app dir并行)目录中

return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}
返回此.http.get('.json'))
.map((响应:响应)=>{
log(“模拟数据”+response.json());
返回response.json();
}
)
.接住(这个.把手错误);
}
注意:这里您只需要在assets文件夹中提供路径,如assets/json/oldjson.json,然后您需要编写路径,如/json/oldjson.json


如果您使用webpack,那么您需要在公用文件夹中遵循上述相同的结构,它类似于资产文件夹。

我认为资产文件夹是公用的,您可以直接在浏览器上访问它

与其他privates文件夹不同,将json文件放到Angular 5中的assets文件夹中

你可以说

this.http.get<Example>('assets/example.json')
this.http.get('assets/example.json'))

这将为您提供可观察的

我需要同步加载设置文件,这是我的解决方案:

export function InitConfig(config: AppConfig) { return () => config.load(); }

import { Injectable } from '@angular/core';

@Injectable()
export class AppConfig {
    Settings: ISettings;

    constructor() { }

    load() {
        return new Promise((resolve) => {
            this.Settings = this.httpGet('assets/clientsettings.json');
            resolve(true);
        });
    }

    httpGet(theUrl): ISettings {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return JSON.parse(xmlHttp.responseText);
    }
}
然后,它作为一个app_初始值设定项提供,在应用程序的其余部分之前加载

应用程序模块.ts

{
      provide: APP_INITIALIZER,
      useFactory: InitConfig,
      deps: [AppConfig],
      multi: true
    },
//在这个组件中,使用suscribe()获取数据,并将其作为dataObject存储在本地对象中,并在display.component.html中显示数据,如{{dataObject.propertyName}

import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
      dataObject :any={};
constructor(private service:ServiceService) { }

  ngOnInit() {
    this.service.getData()
      .subscribe(resData=>this.dataObject =resData)
}
}

您不需要HttpClient,甚至不需要Angular。您只需要WebPack和JSON加载程序,它们都已经是Angular CLI的一部分

您需要的所有代码都是这一行:

import * as someName from './somePath/someFile.json;
您的json数据可以在
someName.default
下找到。但是,此代码将从TypeScript编译器抛出一个类型错误-这不是真正的错误,只是一个类型错误

要解决此问题,请将此代码添加到
src/typings.d.ts
文件中(如果不存在,请创建):


请注意:使用此方法将在构建时将json(minify/uglify)编译到应用程序包中。这意味着您无需等待此文件加载—如果您选择使用
httpClient.get(…)
,则无需等待—这意味着应用程序更快

例如,在声明@component之前在组件中

public init(){
归来(
获取(“assets/server config.json”)。然后(响应=>{
返回response.json();
})
)
.烟斗(
映射(配置=>{
返回配置;
})
)
.toPromise();

}
请将代码和错误发布为文本,而不是屏幕截图,因为屏幕截图不可搜索。/src/app/xy.json中的文件位于此.http.get(./app/xy.json)@yonexbat…这取决于您编写此代码的ts文件的位置。这并不总是正确的…我创建了另一个文件夹,并试图访问该文件,但它没有工作。它将json文件保存在assets文件夹中的唯一方法。不知道为什么会这样。因为您的组件文件夹只能有四种类型的文件:1)“.html”2)“.css”或“.scss”3)“.spec.ts”4)和您的“component.ts”文件。除了这四种类型之外,您不能添加任何其他类型,如.json。其他类型的图像,如:.png、.jpeg或.json,需要保存在“app”文件夹之外。在catch语句中,您可能应该返回错误,因为您正在将其记录在构造函数中,对吗?PS:有时如果json无效,则必须使用
res.text()
而不是
res.json()
.map
@Jeff
控制台时。log
返回
未定义
,并记录错误。这对我来说很有用@就像我说的,这是解决我的问题的办法,但是你的贡献可能会帮助其他人。谢谢。我们还需要在app.module.ts文件中定义.json文件吗?它向我抛出了一个“未找到”的错误。你能对此提出建议吗。我的意思是,在本地主机上找不到file.json,因为它没有部署。@prasanasasne如果您使用angular cli,您可以将文件移动到assets文件夹,然后调用get函数作为
assets/file.json
,这样可能行得通。如果您发布一个单独的问题,我可以显示angular cli的配置,以使用另一个文件中的文件。我尝试了此解决方案,但仍会出现模块错误,我是否遗漏了一些内容?@RossRawlins,您遇到了什么错误?从哪一行?在我尝试构建模块“../../../../assets/countries”时,无法找到该模块。这是去t的路吗
declare module "*.json"
{
  const value: any;
  export default value;
}
const en = require('../assets/en.json');