Angular:无法使用HttpClient获取本地json [英] Angular : Unable to GET local json using HttpClient
问题描述
我使用 Angular5
中提供的最新 HttpClient
组件来为本地json发出get请求但我是从此获得404。我已经在我的 app.module.ts
中导入了 HttpClientModule
模块。
I am using the latest HttpClient
component provided in Angular5
to make a get request for local json but I am getting 404 ever since. I have already imported HttpClientModule
module in my app.module.ts
.
文件夹结构快照:
我正在通过blog-detail组件为 blog-list.json
进行调用。这是我的代码:
I am making the call from blog-detail component for blog-list.json
. Here is my code:
constructor(private http: HttpClient) {
}
ngOnInit(): void {
// this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe((data:Blog[]) => {
this.http.get('app/api/blog-list.json').subscribe((data:Blog[]) => {
this.blogs = data;
});
}
我收到以下错误:
GET http://localhost:909/app/api/blog-list.json 404 (Not Found)
即使我尝试通过点击 http:// localhost:909 / src / app / api / blog-list.json 我得到了那里提供的应用程序而不是json文件。
Even if I try to open the file in browser directly by hitting http://localhost:909/src/app/api/blog-list.json I get the application served there instead of the json file.
请注意,对web上的rest api的注释请求是成功的,但是只能调用本地json文件。
Please note that the commented request to a rest api on web is successful but fails for call only to a local json file.
推荐答案
我能解决这个问题,但有点奇怪,为什么它发生在第一个地方。
I was able to fix this but its kinda weird that why it happened at the first place.
为此我必须更新.angular- cli.json并在assets属性中添加api文件夹的路径。现在资产属性看起来像:
For this I had to update the .angular-cli.json and add the path to api folder in assets property. Now the assets property looks like:
"assets": [
"assets",
"app/api",
"favicon.ico"
]
这篇关于Angular:无法使用HttpClient获取本地json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!