在組件 service.ts url: "http://localhost:4200/data/products.json" not found

托尼1957

我在這行代碼“return 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))
      );
  }
}
母體

嘗試將您的 json 文件夾放在 assets 文件夾下,如下所示:

src\assets\mock\products.json

然後修改方法中的路徑:

getAll(): Observable<Product[]> {
    return this.http.get<Product[]>('assets/mock/products.json')
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用 URL 中的參數路由到組件

將動態 tailwind 類添加到 react 組件(Next.JS + Tailwind + TS)

組件 url 顯示的是應用程序中任意 url 地址的主頁

如何在不使用 <Link> 組件的情況下更改 URL?

React Router history.push() 更改了 url 但未呈現組件內容

為新的 Lightning Web 組件/銷售人員查找或創建 URL

存储来自service.ts的数据以在同一service.ts中使用

单击按钮以从ts函数打开url

Error starting docker service: Unit not found

订阅的值在 component.ts 中返回 undefined 但在 service.ts 中存在值

我的 service.ts 没有在我的组件中调用?

在angular service.ts中使用Google的api.js

通过 Service.ts 从 BlobStorage 获取数据并调用函数 NgOnit

将数据从service.ts传输到组件

如何将 Service Worker 从 JS 迁移到 TS

在角度6中从service.ts返回undefined

如何在 angular service.ts 中传递修复变量?

将 id 从组件传递给 service.ts Angular

从Angular Service获取上传URL

TS 4.0可变参数元组和中间件模式

'以角度导入admin.service.ts文件时找不到模块'./admin.service'吗?

組件的角度路由

Django Media URL返回404 Not Found

GoogleSheet: IMPORTXML error, resource at url not found?

关于目标 URL 的 Angular 404 Not Found

TypeScript 錯誤 7053 - 創建一個使用 prop 覆蓋樣式的自定義 React 組件,我如何正確告訴 TS 類型是什麼?

傳遞一個 React 函數式組件作為函數的參數時,我應該如何用 TS 聲明函數參數類型

如何绑定选择/选项值以在service.ts中而不是component.ts中获得请求功能(角度8)

有沒有辦法通過使用 redux 和 react-router 更改 url 來強制更新組件?