We regret to inform you that the InMemoryWebApiModule is currently experiencing a status of 404,

I'm currently working on implementing the InMemoryWebApiModule with angular2 and creating a mock backend server using the InMemoryDbService. I have configured everything according to what I believed was correct, but for some reason, I am unable to access the data structure that is supposed to implement the InMemoryDbService (WorkerData in worker.ts). Instead, I keep receiving a status 404 error stating "Collection 'workers' not found". I have simplified my code for better clarity, and it seems like there is an issue with the URL - however, I can't seem to figure out why.

The problem arises when I try to execute the getWorkers function in the service. Below is a snippet of my code:

import { WorkerData } from './Services/worker';
import {InMemoryWebApiModule } from 'angular-in-memory-web-api';
@NgModule({
 imports: [ BrowserModule, HttpModule, ReactiveFormsModule, FormsModule, 
    RouterModule, routes, InMemoryWebApiModule.forRoot(WorkerData) ],
 declarations: [ ... ],
providers: [ WorkerService],
bootstrap: [ AppComponent ]
})
export class AppModule { }

worker.ts:

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

export interface IWorker
{
    id: number;
    IDNumber: number;
    FirstName?:string;
    LastName?:string;
    Email? : string;
    DateOfBirth?: string;
    PhoneNumber1?: string;
    PhoneNumber2?: string;
    Street1? :string;
    Street2?: string;
    City?: string;
    Zip?:number;
    General_Additional_Data?: string;
}

 @Injectable()
 export class WorkerData implements InMemoryDbService
 {
     createDb()
     {
       let workers = 
        [{
         "id": 1,
         "IDNumber": 289156,
         "FirstName":"qqqqqq",
         "LastName":"cccccc",
         "DateOfBirth": "02/11/1991",
         "PhoneNumber1": "3422-088808",
         "PhoneNumber2":"3234-6321223",
         "General_Additional_Data": "qqqqqqqqqqqqq"
     },
     {
         "id": 2,
         "IDNumber": 289157,
         "FirstName":"aaaaaaa",
         "LastName":"bbbbbbb",
         "DateOfBirth": "05/11/1981",
         "PhoneNumber1": "02328-08434348",
         "PhoneNumber2":"052322-63213434",
         "General_Additional_Data": "efefsdfsdfs"
     },
     {
         "id": 3,
         "IDNumber": 289466,
         "FirstName":"aaaaa",
         "LastName":"bbbbbb",
         "DateOfBirth": "05/1/1991",
         "PhoneNumber1": "0328-45634348",
         "PhoneNumber2":"3232-7613434",
         "General_Additional_Data": "aaaaaaaaaaaaaaaaa"
     }];
     return workers;
 }
 }


export class Worker implements IWorker{

constructor(
    public id =-1,
    public IDNumber = -1,
    public FirstName?:string,
    public LastName?:string,
    public Email? : string,
    public DateOfBirth?: string,
    public PhoneNumber1?: string,
    public PhoneNumber2?: string,
    public Street1? :string,
    public Street2?: string,
    public City?: string,
    public Zip?:number,
    public General_Additional_Data?: string
){}

}

WorkerService.service (in the same folder as the worker.ts above is):

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

import { IWorker, WorkerData } from './Services/worker';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

@Injectable()

export class WorkerService
{
    private _workerURL = 'api/workers';
    constructor (private _http: Http){}
        getWorkers(): Observable<IWorker[]>
        {
            return this._http.get(this._workerURL)
                       .map((response : Response) => <IWorker[]> 
                        response.json())
                        .do(data => console.log('All: ' + 
                        JSON.stringify(data)))
                       .catch(this.handleError);
       }

Answer №1

It appears there may be a misconfiguration with the object returned from the createDb function. According to the documentation, this object should be:

a hash with collection names as keys and arrays of collection objects as values.

In the provided example, you are returning an array directly from createDb, which is the workers collection itself. Instead, you should return an object as specified:

return { workers: workers };

-or-

return { workers }; // Shorter form of the previous code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the TypeScript compiler not recognizing tsconfig.json?

I recently came across a file from a tutorial that has left me confused due to the inconsistency between documentation, tutorials, and examples: /scripts/tsconfig.json: { "compilerOptions": { "emitDecoratorMetadata": true, "experiment ...

Error parsing the JSON data was encountered

I encountered an error while parsing json data. Here is the json snippet: [{ "name": "TqgQdaaqQU", "location": "YEyFMkCiAjGRsxa", "type_id": 68, "gos_prinad_id": 64, "disloc_country_id": 95, "adm_terr_id": 57, "lat": 142.48 ...

What is preventing Angular from functioning as the default folder homepage in Outlook 2013?

Trying to replicate the functionality of the Outlook Kanban board using Angular has been a bit challenging for me. I managed to create the application successfully and made it work in IE11. However, when I set it as the homepage for my task folder in Outlo ...

I am searching for answers to solve issues related to a JSON file

I am currently working on a tool that searches for matches in an input field by comparing the keywords entered by the user with a JSON. During my testing phase, I focused on using a single API that provides information about different countries and fortun ...

How can Angular 4 manage an object containing other objects most effectively?

Who can guide me on the best way to handle a data structure like this: { "1":{ "id":"1", "name":"Facebook", "created_at":"", "updated_at":"", "fields":{ "1":{ "id":"1" ...

Switch the orientation of the content flow in bootstrap columns from horizontal to vertical

I am currently working on a file explorer project and I have run into an issue with the layout. My goal is to create a layout similar to Windows file explorer, where files are displayed vertically. However, my current code is arranging them horizontally li ...

Deleting button on Angular 4's CKEditor

Currently, I am utilizing version 4.7.3/basic/ckeditor.js and seeking guidance on how to eliminate the "About" and "NumberedList" buttons. Does anyone have a solution for this? <ckeditor [(ngModel)]="work.points" [config]="{removePlugins: 'Ab ...

Using Selenium WebDriver to Perform Drag and Drop Functionality on an Angular/Material Design Website

I've been attempting to automate the drag and drop event using Selenium Java WebDriver on a website built with Angular/Material design. Despite trying numerous approaches, none have been successful - there are no error messages, but the dragging and d ...

Do not prerender certain authorized modules in Angular 7 and maintain the standard angular functionality

My issue involves certain modules that only authorized users can access, and since I rely on SSR for SEO purposes, there is no need for them to be prerendered. The problem lies in how to render these modules because the node server is unauthorized, and th ...

Menu item currently unavailable

I am looking to disable the selected item menu when it is clicked until there is no response. I am curious if there is a universal way to achieve this. For example: <ng-template [ngIf]="item.hasSidebar"> <li [hidden]="itemHidden(item.keyPa ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

How can you determine if the useHash property of RouterModule is true in Angular 8?

Currently, I am working on developing a library for my job that will allow other development teams to utilize some of our Angular components and customize them with their own configurations. One key component is the RouterModule. While examining the code ...

Looping through Angular variables within a component

As soon as I update the value of a property within a component's class that is being used in a loop, the value reverts back to its original state. This behavior does not occur when the component is used in isolation, without being part of an *ngFor lo ...

Validation for Angular nb-step and nb-select components

Looking at this code snippet: <nb-stepper #stepper orientation="horizontal"> <!-- **************** STEP N1 **************** --> <nb-step [label]="labelOne"> <ng-template #labelOne>Area</ng-temp ...

Encountering an issue while attempting to upload information - Angular

Hey there, I'm encountering an issue when trying to submit data to the Server. Here is the code snippet: Service.ts: @Injectable({providedIn: 'root'}) export class ArticlesService { constructor(private http: HttpClient) { } createAr ...

Determine whether an object possesses a property of a specific data type

I am currently exploring the use of generics in converting a date split into multiple parts into a Date object. Here is what I have so far: export const convertDate = <T, K extends keyof T>(obj: T, key: K) => { const k = String(key) const [mo ...

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...

Function `getEventMap` that retrieves the specific "EventMap" associated with an EventTarget T

In the file lib.dom.d.ts, there is a defined interface: interface EventTarget { addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void; dispatchEvent(event: Event): boo ...

What could be the reason for the bootstrap carousel failing to load on Angular 17 SSR?

Using bootstrap, I copied a snippet from the bootstrap page and made some modifications to utilize @for because my image is coming from a service. Below is the code I used: <div class="container"> <div class="carousel"> ...