错误:使用in-memory-web-api时未找到集合

时间:2017-03-23 19:20:11

标签: json angular

如何在 in-memory-web-api 中使用Angular2的Http方法?

我公司目前已开始申请,我们正在使用Angular2作为前端选择。由于我们仍然没有后端部分,因此我们使用in-memory-web-api。我有一个json文件位于Angular2结构的assets文件夹中,我使用Http方法和Observables构建了CRUD。如果我注释掉**in-memory-web-api**我可以向json文件的所有对象发出get请求,但是我无法发布帖子,或者通过参数获取对象,所以我需要“in-memory -web-api“。   如果我在尝试获取json文件的所有对象时使用“in-memory-web-api”,则会出现以下错误

  

未找到收集'产品'

2 个答案:

答案 0 :(得分:1)

import { InMemoryDbService } from 'angular-in-memory-web-api';

import { IProduct } from './product';
import {IInfo} from '../Informations/Model/info'

export class ProductData implements InMemoryDbService{

createDb() {

 let infos : IInfo[] = [

 {   "id":1,
    "Name": "Some Name",
   "Surname": "Bla Bla bla",
   "Country": "Austria",     
  "otherInfo":['24','Wien']

},
   {
   "id":2,
  "Name": "Another Name",
    "Surname": "Nla bla",
    "Country": "Norway",
    "otherInfo":['24','Trondheim']

  }


];


 let products: IProduct[] = [
       {              
               'id':1,
             'productName': 'IPAD',
             'productCode': 'GDN-0011',
             'releaseDate': 'March 19, 2016',
             'description': 'Easy Use',
             'price': 1945.95,
             'starRating': 4.2,
            'imageUrl': '',

         },
         {
             'id': 2,
             'productName': 'Mac Book',
             'productCode': 'GDN-0023',
             'releaseDate': 'March 18, 2016',
            'description': 'Excellent',
           'price': 1632.99,
            'starRating': 4.8,
            'imageUrl': ''
        }
    ];
     return { products,infos};
  }
}

现在您可以在服务中使用网址了 api / infos或api / products

答案 1 :(得分:0)

我想在此问题中强调一件事,如果您使用的是“内存中的Web API”,并且如果您尝试调用实时运行的API,或者您尝试调用位于Asset文件夹中的任何JSOn文件数据,您将在控制台日志中获取未找到特定集合的错误。原因是'In -memory-web-Api'将模拟你的json调用或web API调用,而angular将查看'in-memory'类,即createDB,最终它不会获得该集合。我建议你不要使用'内存Web API',而是使用JSON文件的集合并注释所有内存Web API参考。它会正常工作。