What is the reason behind In-memory-web-api not generating an ID?

While I have successfully implemented the GET, PUT, and DELETE methods using InMemoryDbService to simulate an API, I am facing issues with the CREATE method. It seems like the ID is not being generated in the route to display my add form. The error message displayed in the console is:

"url: 'api/pokemons/NaN'" and body : {error: "pokemons" with id = 'NaN' not found"

To keep things concise, I have omitted showing the mock-pokemon-list.ts file which simply consists of an array of data. Additionally, I have removed the methods that are functioning correctly from my files for clarity and ease of reading. I have already attempted to resolve this issue by referring to this topic on Stack Overflow: why genID() method in In-memory-web-api does not generate an ID? ... I hope my query is comprehensible and straightforward. Apologies for the length of the files. Thank you!

pokemon.module.ts (routes)

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { PokemonService } from './pokemon.service';
import { FormsModule } from '@angular/forms';
import { PokemonFormComponent } from './pokemon-form/pokemon-form.component';
import { AddPokemonComponent } from './add-pokemon/add-pokemon.component';

const pokemonRoutes: Routes = [
  { path: 'pokemon/add', component:AddPokemonComponent},
  
]
    
@NgModule({
  declarations: [
    PokemonFormComponent,
    AddPokemonComponent
    
  ],
  imports: [
    CommonModule,
    FormsModule,
    RouterModule.forChild(pokemonRoutes)
  ],
  providers: [PokemonService],
})
export class PokemonModule { }


in-memory-data-service.ts (we import data from mock-pokemon-list.ts which uses pokemon.ts class just after)

import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { POKEMONS } from './pokemon/mock-pokemon-list';

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

  createDb() {
    const pokemons= POKEMONS;
    return { pokemons };
  }
}

pokemon.ts

export class Pokemon {
    id:number;
    name:string;
    hp:number;
    cp:number;
    picture:string;
    types:string[];
    created:Date;

  constructor(
    name:string = 'Enter a name...',
    hp: number = 100,
    cp: number = 10,
    picture: string = 'https://assets.pokemon.coom/assets/cms2/img/pokedex/detail/xxx.png',
    types:string[] = ['Normal'],
    created: Date = new Date()
  ) {
    this.name=name;
    this.hp=hp;
    this.cp =cp;
    this.picture = picture;
    this.types = types;
    this.created = created;
  }
     
  
}

imports and add method in pokemon.service.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Pokemon } from './pokemon';
import { catchError, Observable,of, tap } from 'rxjs';


@Injectable()
export class PokemonService {

  constructor(private http: HttpClient){}

 addPokemon(pokemon:Pokemon):Observable<Pokemon>{
  const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json'})
  };
  return this.http.post<Pokemon>('api/pokemons', pokemon, httpOptions).pipe(
    tap((response)=> this.log(response)),
    catchError((error)=>this.handleError(error, null))
  )
 }
 
  private log(response: any) {
    console.table(response);
  }
  private handleError(error: Error, errorValue: any) {
    console.error(error);

    return of (errorValue);
  }
  
}

add-pokemon.component.ts (a component which uses pokemon-form just below)

import { Component, OnInit } from '@angular/core';
import { Pokemon } from '../pokemon';

@Component({
  selector: 'app-add-pokemon',
  template: `
    <app-pokemon-form [pokemon]="pokemon"></app-pokemon-form>
  `,
})
export class AddPokemonComponent implements OnInit {

  pokemon:Pokemon;

  ngOnInit(): void {
    this.pokemon = new Pokemon();
  }

}

pokemon-form.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Pokemon } from '../pokemon';
import { PokemonService } from '../pokemon.service';

@Component({
  selector: 'app-pokemon-form',
  templateUrl: './pokemon-form.component.html',
  styleUrls: ['./pokemon-form.component.css']
})
export class PokemonFormComponent implements OnInit {

  @Input() pokemon:Pokemon;
  types: string[];
  isAddForm:boolean;

  constructor(
    private router:Router,
    private pokemonService: PokemonService
  ) { }


  ngOnInit()  {

    this.isAddForm = this.router.url.includes('add');
  }
    

  onSubmit() {
    if(this.isAddForm) {
      this.pokemonService.addPokemon(this.pokemon)
      .subscribe((pokemon: Pokemon)=> this.router.navigate(['/pokemon', pokemon.id]));
    }else {
      this.pokemonService.updatePokemon(this.pokemon)
      .subscribe(() => this.router.navigate(['/pokemon', this.pokemon.id])); 
    }
    
  }
}

my button which initiates the action

<a class="btn-floating btn-large waves-effect waves-light red z-depth-3"
  style="position: fixed; bottom: 25px; right: 25px;" routerLink="/pokemon/add"> + </a>

Answer №1

After reviewing your code, it appears that when you navigate to /pokemon/add, you should be using the AddPokemonComponent instead of the DetailPokemonComponent.

const pokemonRoutes: Routes = [
  { path: 'edit/pokemon/:id', component: EditPokemonComponent},
  { path: 'pokemons', component: ListPokemonComponent },
  { path: 'pokemon/:id', component: DetailPokemonComponent},
  { path: 'pokemon/add', component: AddPokemonComponent},
]

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

Encountered difficulties in deploying functions on Firebase Cloud Functions

While developing the Firebase Cloud Functions, I organized the files based on each function. Unfortunately, numerous errors occurred during deployment. Error [debug] [2022-07-19T14:36:17.677Z] <<< [apiv2][body] GET https://us.gcr.io/v2/xxxxxx/gcf ...

Learn how to navigate through the extensive file structure in Eclipse's Project Explorer after compiling the Angular 2 tutorial 'Tour of Heroes'

I am currently in the process of learning AngularJS 2 using the 'Tour of Heroes' tutorial with Typescript. Everything has been going well so far, but I have noticed something peculiar while working on this tutorial. After compiling with NodeJs, a ...

Guide on achieving horizontal scrolling in Ionic 3

Check out this image I have a list of 10 names in an ion-scroll, but they are appearing on separate lines like paragraphs. Below is my HTML code: <ion-scroll scrollX="true" style="width:100vw; height:50px" > <ion-row class="headerChip"& ...

Error: The Class 'Subject<T>' does not properly extend the base class 'Observable<T>'

I encountered an error that says: **Build:Class 'Subject<T>' incorrectly extends base class 'Observable<T>** . I have TypeScript 2.4.1 installed and obtained angular quick starter files from the GitHub repository angular quick ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

Adjusting the background color of the custom input range thumb when the input is disabled

I've customized the input thumb on my range slider, and I'm looking to change its color when it's disabled. I attempted adding a class to the thumb like this: input[type=range]::-webkit-slider-thumb.disabled and also tried adding the disa ...

Encountering unexpected errors with Typescript while trying to implement a simple @click event in Nuxt 3 projects

Encountering an error when utilizing @click in Nuxt3 with Typescript Issue: Type '($event: any) => void' is not compatible with type 'MouseEvent'.ts(2322) __VLS_types.ts(107, 56): The expected type is specified in the property ' ...

Array containing HTML code for Ionic framework

Just starting out with Ionic/Angular and I have a question. How can I display an array containing HTML content? { "code" : "06", "descr" : "Some text:</br>Other text.<br/>Other text</br>Other text." } When I try to print it, the HTML ta ...

What is the best way to incorporate a @types module into a TypeScript file that is not already a module?

Setting the Stage: In the process of shifting a hefty ~3,000 line inline <script> from a web-page to a TypeScript file (PageScripts.ts) to be utilized by the page through <script src="PageScripts.js" defer></script>. This script entails ...

When the back button is pressed on android, the navbar does not immediately refresh the active class

When using a webapp on Chrome for Android, pressing the back button results in double active items in the navbar. Clicking outside of the navbar removes the old active item. I attempted to resolve the issue by adding [routerLinkActiveOptions]="{ exact: tr ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Tips on utilizing array filtering in TypeScript by solely relying on index rather than element callback

When running tslint, I encountered the following error message: https://i.sstatic.net/p2W9D.png Is it possible to filter based on array index without utilizing element callback? Any alternative suggestions would be appreciated. ...

Seamless conversion

I have a web application created using Angular framework. Below is the code snippets for the template file and TypeScript file: HTML: <button class="btn btn-primay" (click)="changeColumnsSize()"> change column sizes</button> <div class=" ...

What is the TypeScript equivalent of the Java interface.class?

Can you write a Java code in TypeScript that achieves the same functionality as the code below: Class<?> meta = Object.class; and meta = Processor.class; // Processor is an interface In TypeScript, what would be the equivalent of .class? Specifica ...

What is the best way to declare a minimum and maximum date in HTML as the current date?

I have a question regarding setting the min/max date for a date input in my Angular 6 project. How can I ensure that only dates up to the current date are enabled? So far, I have attempted to initialize a new Date object in the ngOnInit function and set t ...

Having issues fetching data from the store with the latest version of Ngrx

I've been trying to integrate ngrx into my Angular project, but I'm facing a challenge with retrieving and displaying data. Despite various attempts based on online resources, I can't seem to fetch the data from the store even though the sta ...

There seems to be an issue with the compatibility between typescript and the current version (4.17.14) of the express-serve-static

Using "@types/express-serve-static-core": "4.17.13", the augmentation of express-serve-static-core is functioning properly: import { Request, Response, NextFunction } from 'express' import { PrismaClient } from '@prisma/c ...

The Angular CLI is consolidating all component styles within the head section of the document

Currently, all CSS for a page's components is being injected into the head of the document. Is it possible to consolidate these styles into a separate file that can be linked in the head of the document, similar to how external CSS libraries like boot ...

Centered title in side menu for Ionic 3

I recently utilized the Ionic CLI to create an Ionic project. The version I am working with is Ionic 3. Currently, I am facing a challenge in centering the title image. Any assistance on this matter would be greatly appreciated. <ion-menu [content]=" ...