我试图在angular 2中加载一个带有http.get()的本地json.我试过一些东西,我在stack上找到的.看起来是这样的:

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

在我的component中,我从@angular/http中 Select 了import HttpResponse.然后我有一个名为loadNavItems()的函数,在这里,我try 使用http.get()加载带有相对路径的json,并使用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);
    }
}

我的local json file看起来是这样的:

[{
        "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:enter image description here

在my html template中,我想循环如下项目:

<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:

enter image description here

推荐答案

MY OWN SOLUTION

I created a new component called test in this folder:

enter image description here

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

enter image description here

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

我的循环是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 { }

Json相关问答推荐

使用jolt删除空对象

Vega-Lite:文本笔画在外部

如何使用PlayWriter循环访问JSON对象

在Reaction中从JSON文件中筛选数组

如何让JSON子查询在没有行的情况下返回空数组而不是NULL

用 Jolt 替换 JSON 中的值

当列为空时从 SQL 获取 JSON

当 JSON 字段名称有空格时,ABAP 中的 JSON 反序列化

使用 jq 获取所有嵌套键和值

在 PowerShell 中通过 aws cli 创建 cloudwatch alert 时出现字符串解析错误

PowerShell:如何将哈希表输出为 json 并使用 foreach 循环将其存储在变量中?

使用 json_query 过滤嵌套列表中的元素

使用 Javascript 判断 JSON 对象是否包含值

如何在 Go 中生成带有排序键的 JSON?

将错误消息作为 JSON 对象发送

使用 jq,将对象数组转换为具有命名键的对象

jQuery循环.each()JSON键/值不起作用

请求返回字节,我无法解码它们

YAML 将 5e-6 加载为字符串而不是数字

为什么 RestTemplate 不将响应表示绑定到 PagedResources?