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

Troubleshooting problem with TypeScript observables in Angular 5

Having trouble with a messaging app, specifically an error related to TS. The syntax checker in the Editor is flagging this issue: Type 'Observable<{}>' is not compatible with type 'Observable'. Type '{}' cannot be assig ...

Problems encountered while building TypeScript on Azure's Hosted Agent

I'm currently working on an ASP.NET MVC application built in .Net5 that utilizes TypeScript files and includes NuGet package references for the following: <PackageReference Include="BuildBundlerMinifier" Version="3.2.449" /> ...

Dynamically modifying the display format of the Angular Material 2 DatePicker

I am currently utilizing Angular 2 Material's DatePicker component here, and I am interested in dynamically setting the display format such as YYYY-MM-DD or DD-MM-YYYY, among others. While there is a method to globally extend this by overriding the " ...

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

Solving CORS policy error in a MEAN stack application deployed on Heroku

I've been grappling with a CORS policy error in my MEAN stack app for quite some time now. The specific error message I keep encountering is: "Access to XMLHTTPRequest at <my heroku app url.com/login> from origin has been blocked by CORS ...

Is there a way to create fresh instances of a class using Injector rather than utilizing a singleton pattern?

In my Angular application, I am working with two injectable classes. @Injectable() class B {} @Injectable() class A { constructor(b:B) { } } My goal is to make class A a Singleton and class B a Transient. I recently discovered that I can utilize Ref ...

Best practices for incorporating CSS and JS files into an Angular deployment

I am currently in the process of integrating an Admin Template that I previously used in a traditional PHP application into a new Angular project. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel= ...

Angular 2 observables not functioning properly with web API

I have been encountering issues while trying to access the WEB API using the http.get method. The service I am implementing utilizes observables, but it does not seem to be functioning properly. There are no calls being made to the server and no error me ...

What is the best way to programmatically click on an element within the body of a webpage from an Angular component?

I am running a crisp chat service on my website and I am attempting to interact with the chat box from one of my component's typescript files. The chat box is represented as a div element with the id crisp-client inside the body tag. Can someone plea ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

Leveraging a ScrollView in an AbsoluteLayout with Angular Nativescript

I have developed a unique photo browsing app that allows users to swipe between pages to view different photos. Currently, I have implemented a working view for this feature. <ScrollView orientation="horizontal" ios.pagingEnabled="true" > <Stac ...

Is there a way for me to simultaneously run a typescript watch and start the server?

While working on my project in nodejs, I encountered an issue when trying to code and test APIs. It required running two separate consoles - one for executing typescript watch and another for running the server. Feeling frustrated by this process, I came ...

"Improve your Angular ngrx workflow by utilizing the sandbox pattern to steer clear of

Currently, I'm trying to determine whether my implementation of the ngrx and sandbox pattern is effective. Here's the issue I'm facing: getFiles(userId: number, companyId: number) { this.fileService.getFiles(userId, companyId).subscribe(re ...

What is the best way to utilize nested components in Angular 2's latest stable release?

When using previous RC releases, we were able to use the directive tag for nested components. However, in the final release of Angular 2, the directive tag has been removed from components. So now, what is the best approach for placing one component inside ...

Tips for toggling visibility in Angular 2

I utilized [hidden] in the following way where the value of "secondTab" is set to true. <form #siteForm="ngForm" novalidate (ngSubmit)="saveSite(siteForm.value,siteForm.valid)" class="admin-modal"> <div class="txt-danger">{{errorMessage}}&l ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

What steps are involved in setting up a sorting feature?

In order to utilize the array.sort() function, a number-returning function must be specified. Typically, it would look something like this: myArray.sort((item1, item2) => a < b); However, I am aiming for a different structure: myArray.sort(by(obj ...

Effective ways to request verification prior to eliminating an item with ng-select (multi-select)

https://i.stack.imgur.com/HDtXq.jpg Is it possible to add a confirmation prompt when deleting an item from a select component? I couldn't find any specific prop for the component. Is there any way to customize or override the delete function? ...

Tips for executing a type-secure object mapping in Typescript

I am currently working on creating a function in Typescript that will map an object while ensuring that it retains the same keys. I have attempted different methods, but none seem to work as intended: function mapObject1<K extends PropertyKey, A, B>( ...

Troubleshooting Angular 2 routes failing to function post aot compilation deployment

Currently, I am implementing RouterModule in my project and have the following configuration in my app.module.ts file: const appRoutes: Routes = [ { path: '', redirectTo: 'mainMenu', pathMatch: 'full' }, { path: 'mainMen ...