使用 angular 2 中的 http.get() 从本地文件加载 json [英] Load json from local file with http.get() in angular 2

查看:30
本文介绍了使用 angular 2 中的 http.get() 从本地文件加载 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 angular 2 中的 http.get() 加载本地 json.我尝试了一些东西,我在堆栈中找到了这些东西.它看起来像这样:

这是我的 app.module.ts,我在其中 import HttpModuleJsonModule>@angular/http:

import { BrowserModule } from '@angular/platform-b​​rowser';从'@angular/core' 导入 { NgModule };从'@angular/forms' 导入 { FormsModule };从@angular/http"导入 { HttpModule, JsonpModule };从@angular/router"导入 { RouterModule, Routes };从 './app.component' 导入 { AppComponent };从 './nav-comp/nav-comp.component' 导入 { NavCompComponent };import { NavItemCompComponent } from './nav-comp/nav-item-comp/nav-item-comp.component';@NgModule({声明: [应用组件,导航组件,导航项组件],进口:[浏览器模块,表单模块,Http模块,Jsonp 模块,RouterModule.forRoot(appRoutes)],提供者:[],引导程序:[AppComponent]})导出类 AppModule { }

在我的组件中,我从@angular/httpimport HttpResponse>.然后我有一个名为 loadNavItems() 的函数,我尝试使用 http.get() 使用相对路径加载我的 json,并使用 console 打印结果.日志().在ngOnInit()中调用该函数:

import { Component, OnInit } from '@angular/core';从@angular/http"导入 { Http, Response };@零件({选择器:'app-nav-comp',templateUrl: './nav-comp.component.html',styleUrls: ['./nav-comp.component.scss']})导出类 NavCompComponent 实现 OnInit {导航项目:任何;构造函数(私有http:Http){}ngOnInit() {this.loadNavItems();}加载导航项目(){this.navItems = this.http.get("../data/navItems.json");console.log(this.navItems);}}

我的本地 json 文件如下所示:

<代码>[{身份证":1,"name": "家","routerLink": "/home-comp"},{身份证":2,"name": "&Uuml;ber uns","routerLink": "/about-us-comp"},{身份证":3,"name": "事件","routerLink": "/events-comp"},{身份证":4,"name": "画廊","routerLink": "/galery-comp"},{身份证":5,"name": "赞助商","routerLink": "/sponsoring-comp"},{身份证":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文件?

解决方案

我自己的解决方案

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

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

这个模拟看起来像这样:

<预><代码>[{身份证":1,"name": "项目 1"},{身份证":2,"name": "项目 2"},{身份证":3,"name": "项目 3"}]

在我的组件的控制器中 test import 按照这样的 rxjs

import 'rxjs/add/operator/map'

这很重要,因为你必须从http get调用中map你的response,所以你得到一个json 并且可以在你的 ngFor 中循环它.这是我如何加载模拟数据的代码.我使用了 http get 并用这个路径调用了我的模拟路径 this.http.get("/assets/mock/test/test.json").在此之后,我 map 响应并subscribe 它.然后我将它分配给我的变量 items 并在我的 template 中使用 ngFor 循环它.我也导出类型.这是我的整个控制器代码:

import { Component, OnInit } from "@angular/core";从@angular/http"导入 { Http, Response };导入'rxjs/add/operator/map'导出类型 Item = { id: number, name: string };@零件({选择器:测试",templateUrl: "./test.component.html",styleUrls: ["./test.component.scss"]})导出类 TestComponent 实现 OnInit {项目:数组<项目>;构造函数(私有 http: Http){}ngOnInit() {这个.http.get("/assets/mock/test/test.json").map(data => data.json() as Array).订阅(数据=> {this.items = 数据;控制台日志(数据);});}}

我的循环是template:

{{项目名称}}

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

import { BrowserModule } from '@angular/platform-b​​rowser';从'@angular/core' 导入 { NgModule };从@angular/http"导入 { HttpModule, JsonpModule };从 './app.component' 导入 { AppComponent };从'./components/molecules/test/test.component'导入{TestComponent};@NgModule({声明: [应用组件,测试组件],进口:[浏览器模块,Http模块,Jsonp 模块],提供者:[],引导程序:[AppComponent]})导出类 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": "&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"
    }
]

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

这篇关于使用 angular 2 中的 http.get() 从本地文件加载 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆