Home > Software design >  angular-in-memory-web-api displays error 404
angular-in-memory-web-api displays error 404

Time:02-16

I done the heroes-tour and I want to do something similar but I have a problem with understand angular-in-memory-web-api. Look at my code: clients-data.service.ts

import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';

@Injectable({
  providedIn: 'root'
})
export class ClientsDataService implements InMemoryDbService{

  createDb(){
    const clients = [
      {id: 1, name: 'Jan Kowalski'},
      {id: 2, name: 'Grzegorz Brzęczyszczykiewicz'},
      {id: 3, name: 'Paweł Nowak'},
    ];
    return clients;
}
  constructor() { }
}

clients.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Client } from './client';

@Injectable({
  providedIn: 'root'
})
export class ClientService {
  private clientsURL = 'api/clients';
  constructor(
    private http: HttpClient,
  ) { }
  getClients(): Observable<Client[]> {
    return this.http.get<Client[]>(this.clientsURL)
  }
}

app.module.ts

//...
    HttpClientInMemoryWebApiModule.forRoot(
      ClientsDataService, { dataEncapsulation: false }
    )
//...

But in console display an error 404 for api/client. Where I make mistake?

CodePudding user response:

your createDb() needs to return an Object of key/value pairs, not an array.

createDb() {
  const clients = [
      {id: 1, name: 'Jan Kowalski'},
      {id: 2, name: 'Grzegorz Brzęczyszczykiewicz'},
      {id: 3, name: 'Paweł Nowak'},
    ]; 
  return {
    clients: clients
  }
}

Or just change your return line to return {clients};

CodePudding user response:

I think the error is in your path.

private clientsURL = 'http://entire-url/api/clients';

Check your entire route, maybe the error is there.

  • Related