内存数据服务中的多个API在Angular 2中不起作用 [英] Multiple API's in in memory data service not working in angular 2

查看:74
本文介绍了内存数据服务中的多个API在Angular 2中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发angular 2应用程序,但尚未创建后端.Angular有一个很棒的功能:在内存数据服务中.

I am developing an angular 2 application but the back end is not created yet. Angular has this great feature: in memory data service.

我已经使它适用于1个数据集,但不适用于多个数据集.

I got it working for 1 dataset already but not for multiple datasets.

在另一个答案中,有人说我可以像这样将它们放在一起:

In another answer someone said I could just put them together like this:

import { InMemoryDbService } from "angular-in-memory-web-api";
export class InMemoryData implements InMemoryDbService {
    createDb() {
        let categories = [
            { id: 1, category: "Person", name: "testname", faName: ""},
            { id: 2, category: "Goods", name: "testname2", faName: "" }
        ];
        let headCategory = [
            { id: 1 , name: "personen" },
            {id: 2 , name: "goederen"}
        ];
        let langText = [
            { langId: 1 , categoryId: 1, text: "testnl" },
            { langId: 2 , categoryId: 1, text: "testfr" },
            { langId: 1 , categoryId: 2, text: "testnl2" },
            { langId: 2 , categoryId: 2, text: "testfr2" },
        ];
        let langs = [
            { id: 1, langName: "Nederlands" , tag : "NL" },
            { id: 2, langName: "Frans", tag : "FR" }
        ];
        return { categories , headCategory , langText , langs };
    }
}

但是它不起作用,它在请求上得到404错误.有谁知道如何正确地将InMemoryDbService用于多个数据集?

But it does not work, It gets 404 error on the requests. Does anyone know how to properly use the InMemoryDbService for multiple datasets?

以下是一些摘要:服务:

Here are some more snippets: services:

import { Injectable } from "@angular/core";
import { Category } from "../models/category";
import { Headers, Http } from "@angular/http";

import "rxjs/add/operator/toPromise";

@Injectable()
export class CategoriesService {
    private Url = "api/categories";

    constructor(private http : Http) {}

    getCategories () : Promise<Category[]> {
        return this.http.get(this.Url)
            .toPromise()
            .then(response => response.json().data as Category[])
            .catch(this.handleError);
    }

    handleError(error : any) : Promise<any> {
        console.error("An error occurred", error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

import { Injectable } from "@angular/core";
import { HeadCategory } from "../models/head-category";
import { Headers, Http } from "@angular/http";

import "rxjs/add/operator/toPromise";

@Injectable()
export class HeadCategoriesService {
    private Url = "api/headCategory";

    constructor(private http : Http) {}

    getHeadCategories () : Promise<HeadCategory[]> {
        return this.http.get(this.Url)
            .toPromise()
            .then(response => response.json().data as HeadCategory[])
            .catch(this.handleError);
    }

    handleError(error : any) : Promise<any> {
        console.error("An error occurred", error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

应用崩溃的地方:

import { Component, OnInit } from "@angular/core";

import { Category } from "../../models/category";
import { HeadCategory } from "../../models/head-category";

import { CategoriesService } from "../../services/categories.service";
import { HeadCategoriesService } from "../../services/head-category.service";

@Component({
    selector: "category-manager",
    templateUrl: "./category-manager.component.html",
    styleUrls: ["./category-manager.component.scss"]
})
export class CategoryManager implements OnInit {
    constructor(
        private categoriesService : CategoriesService,
        private headCategoriesService : HeadCategoriesService,
    ) {}
    title = "CategoryManager";
    Categories : Category[];
    HeadCategories : HeadCategory[];
    SelectedHeadCategory : HeadCategory;
    getCategories() : void {
        this.categoriesService.getCategories().then(Categories => this.Categories = Categories);
    }
    getHeadCategories() : void {
      this.headCategoriesService.getHeadCategories().then(headCategories => this.HeadCategories = headCategories);
    }
    ngOnInit() {
      this.getHeadCategories();
      this.getCategories();
      this.SelectedHeadCategory = this.HeadCategories[0];
    }
    clickHandler(selectedHeadCategory : HeadCategory ) : void {
      this.SelectedHeadCategory = selectedHeadCategory;
    }

}

推荐答案

这是我使用多个API的InMemoryDbService:

This is my InMemoryDbService where I have used multiple APIs:

import { InMemoryDbService } from 'angular-in-memory-web-api';
import { OrderRequest } from '../../order-window/order-request';
import { Location } from '../location/location';

export class InMemoryDataService implements InMemoryDbService {

createDb() {
let orderRequests: OrderRequest[] = [
  {
    id: 1,
    fullname: 'Jack',
    tel: 4444444,
    watel: 4444444,
    confirmationId: 654645,
    location: 'Bangalore',
    mail: 'jack@gmail.com',
    manual: 'This is testing',
    termsAccepted: true,
    uFile: ''
  }
];

let locations: Location[] = [
  {
      location: 'RT Nagar'
  },
  {
      location: 'Hebbal'
  },
  {
      location: 'Sanjay Nagar'
  },
  {
      location: 'Malleswaram'
  },
  {
      location: 'Sadashivanagar'
  }
];
return {orderRequests, locations};

}}

这是我的LocationService:

This is my LocationService:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Location } from './location';

@Injectable()
export class LocationService {

private _locationUrl = 'api/locations';

constructor(private _http:Http) {}

getLocations(): Promise<Location[]> {
    return this._http.get(this._locationUrl)
    .toPromise()
    .then(response => response.json().data as Location[])
    .catch(this.handleError);
}

private handleError(error: Response) {
    console.error(error);
    return Promise.reject(error.json().error || 'Server error');
}
}

这是我的OrderRequestService:

This is my OrderRequestService:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { OrderRequest } from '../order-window/order-request';

import 'rxjs/add/operator/toPromise';
@Injectable()
export class AdminService {

private headers = new Headers({ 'Content-Type': 'application/json' });
private url = 'api/orderRequests';  // URL to web api

constructor(private http: Http) { }
 getOrderRequests(): Promise<OrderRequest[]> {
  return this.http.get(this.url)
  .toPromise()
  .then(response => response.json().data as OrderRequest[])
  .catch(this.handleError);
 }

 create(orderRequest: OrderRequest) {
  console.log('Create object called. Value is: ' + JSON.stringify(orderRequest));
return this.http
.post(this.url, JSON.stringify(orderRequest), { headers: this.headers})
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}

update(orderRequest: OrderRequest): Promise<OrderRequest> {
const url = `${this.url}/${orderRequest.id}`;
return this.http
  .put(url, JSON.stringify(orderRequest), { headers: this.headers })
  .toPromise()
  .then(() => null)
  .catch(this.handleError);
}

delete(id: number): Promise<void> {
const url = `${this.url}/${id}`;
return this.http.delete(url, { headers: this.headers })
  .toPromise()
  .then(() => null)
  .catch(this.handleError);
}

private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}

我的服务运行正常.尝试找出错误的地方.

My services are working fine. Try to find out where you have made a mistake.

这篇关于内存数据服务中的多个API在Angular 2中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆