【发布时间】: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