用角度为2的http.get()从本地文件加载json [英] Load json from local file with http.get() in angular 2
问题描述
我试图在角度2中加载一个带有 http.get()
的本地json。我尝试了一些我在堆栈中找到的东西。它看起来像这样:
这是我的 app.module.ts
其中I import
HttpModule
和 JsonModule
来自 @ angular / http
:
$ b
从'@ angular / platform-browser'导入{BrowserModule};
从'@ angular / core'导入{NgModule};
从'@ angular / forms'导入{FormsModule};
从'@ angular / http'导入{HttpModule,JsonpModule};
从'@ angular / router'导入{RouterModule,Routes};
从'./app.component'导入{AppComponent};
从'./nav-comp/nav-comp.component'导入{NavCompComponent};
从'./nav-comp/nav-item-comp/nav-item-comp.component'导入{NavItemCompComponent};
$ b @NgModule({
声明:[
AppComponent,
NavCompComponent,
NavItemCompComponent
],
进口:[
BrowserModule,
FormsModule,
HTTP模块,
JsonpModule,
RouterModule.forRoot(appRoutes)
]中,
提供商: ],
bootstrap:[AppComponent]
})
export class AppModule {}
在组件中,< Http
和 Response
来自 @ angular / http
。然后我有一个名为 loadNavItems()
的函数,我尝试使用相对路径使用 http.get()$ c $加载我的json c>并用
console.log()
打印结果。该函数在 ngOnInit()
中调用:
import {Component, OnInit} from'@ angular / core';
从'@ angular / http'导入{Http,Response};
@Component({
选择器:'app-nav-comp',
templateUrl:'./nav-comp.component.html',
styleUrls: ['./nav-comp.component.scss']
})
导出类NavCompComponent实现OnInit {
navItems:any;
构造函数(private http:Http){}
ngOnInit(){
this.loadNavItems();
loadNavItems(){
this.navItems = this.http.get(../ data / navItems.json);
console.log(this.navItems);
我的本地json文件看起来像这样:
[{
id:1,
name:Home ,
routerLink:/ home-comp
},
{
id:2,
name:& Uuml; ber $ uns,
routerLink:/ about-us-comp
},
{
id:3,
name: Events,
routerLink:/ events-comp
},
{
id:4,
name:Galerie,
routerLink:/ galery-comp
},
{
id:5,
name:Sponsoren,
routerLink:/ sponsoring-comp
},
{
id:6,
name:Kontakt,
routerLink :/ contact-comp
}
]
错误在控制台,我只是得到这个输出:
在我的 html模板中,我想循环这些项目:
< app-nav-item-comp * ngFor =let item of navItems[item] =item>< / app-nav-item-comp>
我在堆栈中找到了一个解决方案,但我不知道为什么它没有' t工作吗?
编辑相对路径:
我的相对路径也出现问题,但我确定它是当我使用 ../ data / navItems.json
时是正确的。在屏幕截图中,您可以选择nav-comp.component.ts,我使用json文件中的相对路径加载json,该文件位于名为data的文件夹中?出了什么问题,控制台打印出一个404错误,因为它无法从相对路径中找到我的json文件?
我自己的解决方案
我在这个文件夹中创建了一个名为 test
的新的组件
:
这个模拟看起来像这样:
[
{
id:1,
name:Item 1
$ id
$ name b
$ b $ 3,
name:Item 3
}
]
在我的组件的控制器中 test
import
关注 rxjs
像这样
import'rxjs / add / operator / map'
这很重要,因为您必须 map
您的响应
> http get 调用,所以你得到一个 json
并且可以将它循环到 ngFor
。这是我的代码,如何加载模拟数据。我使用了 http
get
,并用此路径 this.http调用了我的路径。获得( /资产/模拟/测试/ test.json)
。在这之后我 map
响应和订阅
它。然后我将它分配给我的变量项目
,并在模板中用
ngFor
code>。我也出口类型。这里是我的整个控制器代码:
从@ angular / core导入{Component,OnInit};
从@ angular / http导入{Http,Response};
导入'rxjs / add / operator / map'
导出类型Item = {id:number,name:string};
@Component({
selector:test,
templateUrl:./test.component.html,
styleUrls:[./test。 component.scss]
})
export class TestComponent implements OnInit {
items:Array< Item>;
构造函数(private http:Http){}
ngOnInit(){
this.http
.get(/ assets / mock / test /test.json)
.map(data => data.json()as Array< Item>)
.subscribe(data => {
this.items = data;
console.log(data);
});
$ / code $ / pre
我的循环是 template
:
< div * ngFor =let item of items>
{{item.name}}
< / div>
它按预期工作!我现在可以在assests文件夹中添加更多模拟文件,只需将路径更改为 json
即可。请注意,您还需要在控制器中导入 HTTP
和 Response
。在你的app.module.ts(main)中也是这样的:
从'@ angular / platform-浏览器;
从'@ angular / core'导入{NgModule};
从'@ angular / http'导入{HttpModule,JsonpModule};
从'./app.component'导入{AppComponent};
从'./components/molecules/test/test.component'中导入{TestComponent};
$ b @NgModule({
声明:[
AppComponent,
TestComponent
],
进口:[
BrowserModule,
HttpModule,
JsonpModule
],
providers:[],
bootstrap:[AppComponent]
})
export class AppModule {}
I'm trying to load a local json with http.get()
in angular 2. I tried something, that I found here on stack. It looks like this:
this is my app.module.ts
where I import
the HttpModule
and the JsonModule
from @angular/http
:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { NavCompComponent } from './nav-comp/nav-comp.component';
import { NavItemCompComponent } from './nav-comp/nav-item-comp/nav-item-comp.component';
@NgModule({
declarations: [
AppComponent,
NavCompComponent,
NavItemCompComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In my component I import
Http
and Response
from @angular/http
. Then I have a function called loadNavItems()
, where I try to load my json with relative path using http.get()
and print the result with console.log()
. The function is called in ngOnInit()
:
import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
@Component({
selector: 'app-nav-comp',
templateUrl: './nav-comp.component.html',
styleUrls: ['./nav-comp.component.scss']
})
export class NavCompComponent implements OnInit {
navItems: any;
constructor(private http: Http) { }
ngOnInit() {
this.loadNavItems();
}
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json");
console.log(this.navItems);
}
}
My local json file looks like this:
[{
"id": 1,
"name": "Home",
"routerLink": "/home-comp"
},
{
"id": 2,
"name": "Über uns",
"routerLink": "/about-us-comp"
},
{
"id": 3,
"name": "Events",
"routerLink": "/events-comp"
},
{
"id": 4,
"name": "Galerie",
"routerLink": "/galery-comp"
},
{
"id": 5,
"name": "Sponsoren",
"routerLink": "/sponsoring-comp"
},
{
"id": 6,
"name": "Kontakt",
"routerLink": "/contact-comp"
}
]
There are no errors in the console, I just get this output:
In my html template I would like to loop the items like this:
<app-nav-item-comp *ngFor="let item of navItems" [item]="item"></app-nav-item-comp>
I made this with a solution I found here on stack, but I have no idea why it doesn't work?
EDIT RELATIVE PATH:
I also get a problem with my relative path, but I'm sure it's the right one when I use ../data/navItems.json
. In the screenshot you can se the nav-comp.component.ts, where I load the json using relative path from the json file which is in the folder called data? What's wrong, the console prints an 404 error, because it can't find my json file from the relative path?
解决方案 MY OWN SOLUTION
I created a new component
called test
in this folder:
I also created a mock called test.json
in the assests
folder created by angular cli
(important):
This mock looks like this:
[
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
},
{
"id": 3,
"name": "Item 3"
}
]
In the controller of my component test
import
follow rxjs
like this
import 'rxjs/add/operator/map'
This is important, because you have to map
your response
from the http get
call, so you get a json
and can loop it in your ngFor
. Here is my code how I load the mock data. I used http
get
and called my path to the mock with this path this.http.get("/assets/mock/test/test.json")
. After this i map
the response and subscribe
it. Then I assign it to my variable items
and loop it with ngFor
in my template
. I also export the type. Here is my whole controller code:
import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'
export type Item = { id: number, name: string };
@Component({
selector: "test",
templateUrl: "./test.component.html",
styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
items: Array<Item>;
constructor(private http: Http) {}
ngOnInit() {
this.http
.get("/assets/mock/test/test.json")
.map(data => data.json() as Array<Item>)
.subscribe(data => {
this.items = data;
console.log(data);
});
}
}
And my loop in it's template
:
<div *ngFor="let item of items">
{{item.name}}
</div>
It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json
. Notice that you have also to import the HTTP
and Response
in your controller. The same in you app.module.ts (main) like this:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
HttpModule,
JsonpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
这篇关于用角度为2的http.get()从本地文件加载json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!