【问题标题】:GET http://localhost:4200/api/x.json 404 (Not Found) - angular 2GET http://localhost:4200/api/x.json 404(未找到)-角度 2
【发布时间】:2017-09-18 14:14:51
【问题描述】:


您好,项目有问题,无法识别 json 文件 - 我不知道为什么。有什么我需要改变或让它发挥作用的吗?


这是我的文件夹:


这是我的服务:

import { Injectable } from "@angular/core";
import { Ibrides } from "./brides";
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

@Injectable()
export class brideService {
private _brideUrl = 'api/brides.json';
constructor(private _http: HttpClient) { };

getBrides(): Observable<Ibrides[]> {

    return this._http.get<Ibrides[]>(this._brideUrl)
        .do(data => console.log('All:' + JSON.stringify(data)))
        .catch(this.handleError)
}
private handleError(err: HttpErrorResponse) {
    console.log(err.message);
    return Observable.throw(err.message);
}
}

这是我的组件


import { Component, OnInit } from '@angular/core';
import { Ibrides } from "./brides";
import { brideService } from "./brides.service"

@Component({
selector: 'pm-brides',
templateUrl: './brides_list.component.html',
styleUrls: []
})
export class bridesListComponent implements OnInit {


    constructor(private _brideService: brideService) {

    }
    errorMessage: string;
    brides: Ibrides[] = [];
    ngOnInit(): void {
    this._brideService.getBrides()
        .subscribe(brides => {
            this.brides = brides
        },

        error => this.errorMessage = <any>error);

    }

}

【问题讨论】:

  • 这显然是因为该 URL 没有可用的 API。当我看到一个 json 文件时,你不需要模拟 API 调用吗?
  • 我有一个内部 json 文件,我只是想给他打电话。
  • _brideUrl设置为'app/api/brides.json',即_brideUrl = 'app/api/brides.json'
  • 尝试使用src 目录设置路径,会起作用。
  • 同样的错误:(

标签: javascript json angular


【解决方案1】:

只需像这样从根级别引用文件:

_brideUrl = 'app/api/brides.json'

更多信息可以参考this

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2018-08-01
    • 2021-06-28
    • 2018-11-10
    • 1970-01-01
    • 2018-05-25
    • 2019-02-04
    • 2018-11-22
    相关资源
    最近更新 更多