Angular 4-HTTP服务404.找不到JSON文件 [英] Angular 4 - HTTP Service 404. JSON file Not Found

查看:190
本文介绍了Angular 4-HTTP服务404.找不到JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular的新手,并且在http服务中遇到问题. 我尝试了这个.http.get(' http://jsonplaceholder.typicode.com/posts/1')作为示例数据,即可正常工作. 但是当我使用this.http.get('src/data/employees.json')时,它显示了404(未找到)

I am new in angular, and I am having problem in http service. I tried this.http.get('http://jsonplaceholder.typicode.com/posts/1') as sample data and it works. But when I used this.http.get('src/data/employees.json') it shows me 404 (Not Found)

employees.service.ts

employees.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class EmployeesService {

    constructor(private http: Http) { }

    getEmployees() {
        this.http.get('src/employees.json')
            .map(response => response.json() )
            .subscribe(result => console.log(result) );
    }

}

app.component.ts

app.component.ts

import { Component } from '@angular/core';
import { EmployeesService } from './employees.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    constructor(private employeesService: EmployeesService){}

    ngOnInit() {
        this.employeesService.getEmployees();
    }

}

推荐答案

如果您使用的是angular cli,则必须通过在.angular-cli.json中进行设置来输出json文件,如下所示:

If you are using angular cli you have to output your json file by setting that up in .angular-cli.json like so:

"assets": [
        "assets",
        "src/employees.json"
      ],

但是我建议在src文件夹内创建一个像data的文件夹,并将所有数据.json放入其中.然后像这样进行assets配置:

But I would recommend to create a folder like data inside your src folder and place all your data .json filed in to it. Then have your assets config like so:

"assets": [
        "assets",
        "data"
      ],

这样,cli将始终输出整个data文件夹,因此您不必分别指定每个.json文件

This way cli will alway output the whole data folder so you do not have to specify each .json file separately

如果您在ng serve期间更改了.angular-cli.json 为使更改生效,您必须重新启动ng serve

In case if you changing .angular-cli.json during ng serve for your changes to take an effect you have to restart ng serve

这篇关于Angular 4-HTTP服务404.找不到JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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