我在这行代码“返回this.http.get('../ data / products.json');”中收到404 not found错误。
其中service.ts文件的路径为“ src \ app \ shared \ services \ product.service.ts”。 json文件的路径为“ src \ data \ products.json”
这是service.ts代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Product {
id: number;
title: string;
price: number;
imageUrl: string;
description: string;
}
@Injectable()
export class ProductService {
constructor(private http: HttpClient) {}
getAll(): Observable<Product[]> {
return this.http.get<Product[]>('../data/products.json');
}
getById(productId: number): Observable<Product> {
return this.http.get<Product[]>('../data/products.json')
.pipe(
map(products => <Product>products.find(p => p.id === productId))
);
}
}
答案 0 :(得分:1)
尝试将json文件夹放在资产文件夹下,如下所示:
src\assets\mock\products.json
,然后在方法中修改路径:
getAll(): Observable<Product[]> {
return this.http.get<Product[]>('assets/mock/products.json')
}