The issue with the tutorial is regarding the addHero function and determining the source of the new id

Whenever I need to introduce a new superhero character, I will utilize

the add(string) function found in heroes/heroes.component.ts

  add(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.addHero({ name } as Hero)
      .subscribe(hero => {
        this.heroes.push(hero);
      });
  }

as well as the

addHero(Hero) function located in heroes.service.ts


  addHero (hero: Hero): Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
      tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
      catchError(this.handleError<Hero>('addHero'))
    );
  }

I am curious to find out where the new ID is being generated from.

Here is a working example: https://stackblitz.com/angular/ombxjmbjedp

Answer №1

Angular leverages the in-memory-web-api module to mimic CRUD operations on a REST API.

This module introduces a custom HttpInterceptor into the chain of interceptors. This interceptor is responsible for generating unique IDs for entities.

// Creating an entity
// Can also update an existing entity if post409 is false.
protected post({ collection, collectionName, headers, id, req, resourceUrl, url }: RequestInfo)
   : ResponseOptions {
  const item = this.clone(this.getJsonBody(req));

  // tslint:disable-next-line:triple-equals
  if (item.id == undefined) {
    try {
      item.id = id || this.genId(collection, collectionName);

You have the option to create your own function for ID generation in your InMemoryDataService. This can be seen in the provided example here:

export class InMemoryDataService implements InMemoryDbService {
 ...

// Overrides the genId method to ensure that a hero always has an id.
// If the heroes array is empty,
// the method below returns the initial number (11).
// if the heroes array is not empty, the method below returns the highest
// hero id + 1.
genId(heroes: Hero[]): number {
  return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
}

Answer №2


    implementHero (hero: Hero): Observable<Hero> {
        return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
          tap((newHero: Hero) => this.log(`added hero with id=${newHero.id}`)),
          catchError(this.handleError<Hero>('implementHero'))
        );
      }

When utilizing this service function, data object is passed from heroes.component.ts as hero: Hero. At this stage, Hero is used as a defined variable.

addHero (hero: Hero): Observable<Hero> {
 // which is then assigned to another instance 
 tap((newHero: Hero) => this.log(`added hero with id=${newHero.id}`));

All the necessary data can be accessed from newHero, allowing access to the id. Thank you

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

Struggling to access the properties of a Material-UI Button

import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiButton from "@mui/material/Button"; import Slider from "@mui/material/Slider"; interface Props { type: "primary" | ...

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed: this.http.request(path, requestOptions); The path is set to: http://localhost:8082/commty/cmng/users and the requestOptions are as follows: { headers: { user: "sdf", pas ...

The successful completion of an Angular2 HTTP request relies on the data obtained from a previous response

I developed a service that performs various http calls with different parameters. quote.service.ts getQuotes(){ let params = { "Type": "BasicDetail", } return this.http.post(this.url,params) .map(res => res.json()) } getOptio ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

Filtering arrays in Angular can be accomplished using a variety of

I am trying to filter an array based on a query but my current code is not working as expected. Here's what I have: filterguideline() { const query = this.recommendationForm.get('guideline').value; if (query !== "") { ...

What steps can be taken to resolve the error message "How can you repair 'Cannot read properties of undefined (reading 'front_default')'?"

I'm encountering an issue while trying to display data from an API. Although I am able to access the data, a perplexing error keeps popping up that I can't seem to troubleshoot. Here's the error message: Uncaught TypeError: Cannot read pr ...

Tips for conducting tests on ngrx/effects using Jasmine and Karma with Angular 5 and ngrx 5

Here is the file that I need to test. My current focus is on some effects service while working with Angular5 (^5.2.0) and ngrx5 (^5.2.0). I have been struggling to properly implement the code below for testing purposes. Any tips or suggestions would be ...

ESLint prohibits the usage of React.StatelessComponent and React.FunctionalComponent within the codebase

Is there a way to restrict the use of React.StatelessComponent or React.FunctionalComponent and only allow React.FC in my code? For instance: export const ComponentOne: React.StatelessComponent<Props> = (props) => { return <....> }; export ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Angular 9: Chart.js: Monochromatic doughnut chart with various shades of a single color

My goal is to display a monochromatic doughnut chart, with each segment shaded in varying tones of the same color. I have all the necessary graph data and just need to implement the color shading. ...

A guide on launching a Vite React application from a subdirectory

Utilizing Vite to develop a React application. Routes.tsx import { RouteObject, createBrowserRouter } from "react-router-dom"; import App from "../layout/App"; import HomePage from "../../feautures/home/HomePage"; import Crea ...

Attempting to start a fresh Angular project using the command line, only to be met with an unexpected error message

⠹ Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41202f263101716f716f71">[email ...

Step-by-step guide on developing an AngularJs provider using TypeScript

As I've developed a Directive that incorporates various Css classes, it would greatly enhance its flexibility if the Css classes could be configured at Application start within the config section. I believe utilizing a provider is the appropriate appr ...

Passing an Array of Objects from a Child Component to a Parent Component in Angular

I have developed two components named parent and child. These components are linked in app.component.html. In the child component, I have an array of objects that I want to display in the parent component using @Output. My desired output is to show each ob ...

Trigger an error in TypeScript with an embedded inner error

Is it possible to throw an Error with an inner Error in TypeScript, similar to how it's done in C#? In C#, you can achieve this by catching the exception and throwing a new one with the original exception as its inner exception: try { var a = 3; ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Angular powered bootstrap modal with a clean and sleek design featuring a transparent header and background

Currently, I am utilizing an Angular-powered Bootstrap modal for a project. The modal content consists of an iframe that functions as a YouTube video player. My objective is to have the background colors of both the modal body and header be transparent, so ...

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

Changing Angular 2 web app code to Ionic 2 mobile app code?

I currently have a web application code that was written using Angular 2. My goal is to create a hybrid mobile application by utilizing Ionic 2 for the same web application. Since Ionic 2 incorporates core concepts of Angular 2, I have a few questions: Is ...