内存数据服务中的多个API不在角度2中工作

时间:2017-03-13 15:53:59

标签: angular

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

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

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



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用于多个数据集?

以下是一些更多代码段: 服务:



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);
    }
}
&#13;
&#13;
&#13;

&#13;
&#13;
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);
    }
}
&#13;
&#13;
&#13;

应用崩溃的地方:

&#13;
&#13;
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;
    }

}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

我解决了这个问题。问题不在于错误中显示的API。问题是我打电话时没有[0]。

答案 1 :(得分:0)

这是我使用多个API的InMemoryDbService:

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:

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:

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);
}
}

我的服务工作正常。试着找出你犯错的地方。