我正在尝试使用 http.get()
在角度 2 中加载本地 json。我尝试了一些东西,我在堆栈上找到了。它看起来像这样:
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 { }
在我的 组件 中我 import
Http
和 Response
来自 @angular/http
.然后我有一个名为 loadNavItems()
的函数,我尝试使用 --- 加载具有相对路径的 json 并使用 http.get()
console.log()
结果。该函数在 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);
}
}
我的 本地 json 文件 如下所示:
[{
"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"
}
]
在我的 html 模板 中,我想循环这样的项目:
<app-nav-item-comp *ngFor="let item of navItems" [item]="item"></app-nav-item-comp>
我用我在堆栈上找到的解决方案做了这个,但我不知道为什么它不起作用?
编辑相对路径: 我的相对路径也有问题,但我确信当我使用 ../data/navItems.json
时它是正确的。在屏幕截图中,您可以看到 nav-comp.component.ts,我使用来自名为 data 的文件夹中的 json 文件的相对路径加载 json?怎么了,控制台打印404错误,因为从相对路径找不到我的json文件?
原文由 webta.st.ic 发布,翻译遵循 CC BY-SA 4.0 许可协议
我自己的解决方案
我在此文件夹中创建了一个名为
test
的新component
:我还在由
angular cli
--- 创建的assests
文件夹中创建了一个名为test.json
的模拟:这个模拟看起来像这样:
在我的组件的控制器中
test
import
跟随rxjs
这样This is important, because you have to
map
yourresponse
from thehttp get
call, so you get ajson
and can loop it in你的ngFor
。这是我如何加载模拟数据的代码。我使用http
get
并用这条路径调用了我的模拟路径this.http.get("/assets/mock/test/test.json")
。在此之后我map
响应和subscribe
它。然后我将它分配给我的变量items
并在我的template
--- 中使用ngFor
循环它。我也导出类型。这是我的整个控制器代码:我的循环是
template
:它按预期工作!我现在可以在 assests 文件夹中添加更多模拟文件,只需将路径更改为
json
。请注意,您还必须在控制器中导入HTTP
和Response
。你的 app.module.ts (main) 也是这样的: