在组件service.ts url:找不到“http:// localhost:4200 / data / products.json”

问题描述 投票:0回答:1

我在这行代码中遇到404未找到的错误“return this.http.get('../ data / products.json');”

其中路径为service.ts文件的“src \ app \ shared \ _ services \ service.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))
      );
  }
}
angular angular-http angular-httpclient
1个回答
1
投票

尝试将您的json文件夹放在资源文件夹下,如下所示:

src\assets\mock\products.json

然后修改方法中的路径:

getAll(): Observable<Product[]> {
    return this.http.get<Product[]>('assets/mock/products.json')
}
© www.soinside.com 2019 - 2024. All rights reserved.