使用角度 2 的 http.get() 从本地文件加载 json

新手上路,请多包涵

我正在尝试使用 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 HttpResponse 来自 @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 许可协议

阅读 429
2 个回答

我自己的解决方案

我在此文件夹中创建了一个名为 test 的新 component

在此处输入图像描述

我还在由 angular cli --- 创建的 assests 文件夹中创建了一个名为 test.json 的模拟:

在此处输入图像描述

这个模拟看起来像这样:

 [
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

在我的组件的控制器中 test import 跟随 rxjs 这样

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你的 ngFor 。这是我如何加载模拟数据的代码。我使用 http get 并用这条路径调用了我的模拟路径 this.http.get("/assets/mock/test/test.json") 。在此之后我 map 响应和 subscribe 它。然后我将它分配给我的变量 items 并在我的 template --- 中使用 ngFor 循环它。我也导出类型。这是我的整个控制器代码:

 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);
      });
  }
}

我的循环是 template

 <div *ngFor="let item of items">
  {{item.name}}
</div>

它按预期工作!我现在可以在 assests 文件夹中添加更多模拟文件,只需将路径更改为 json 。请注意,您还必须在控制器中导入 HTTPResponse 。你的 app.module.ts (main) 也是这样的:

 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 { }

原文由 webta.st.ic 发布,翻译遵循 CC BY-SA 3.0 许可协议

将您的 navItems.json 放在“assets”文件夹中。 Angular 知道如何查看资产文件夹。所以而不是:

 loadNavItems() {
    this.navItems = this.http.get("../data/navItems.json");
    console.log(this.navItems);
}

将路径更改为:

     loadNavItems() {
    this.navItems = this.http.get("assets/navItems.json");
    console.log(this.navItems);
}

原文由 Philip Owino 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题