Angular 17 in-memory-web-api cannot find the route to the in-memory data?

434 Views Asked by At

I am new to Angular. I followed the Tour of Hero tutorial to the step of using httpClient to retrieve data from the in-memory-web-api. I got an error of 'Unexpected token '<', "<!DOCTYPE "... is not valid JSON'. status code is: 200. I inspect the network traffic on the developer tool and noticed that the URL is : localhost/4200. The response is the entire html of the page. It should be just the json data. I also got the following run time error in the terminal : ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: 'api/heroes'

what am I missing? I did not define any routes.

The app.config.ts is the following:

    export const appConfig: ApplicationConfig = {
      providers: [
        provideRouter(routes),
        provideClientHydration(),
        importProvidersFrom(HttpClientModule),
        //provideHttpClient(withFetch()),
        importProvidersFrom(HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService))
      ]
      
    };

hero.service.ts:

import { Injectable } from '@angular/core';

    import { Hero } from './hero';
    import { HttpClient } from '@angular/common/http';
    import {
      Observable,
      catchError,
      tap,
    } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class HeroService {
      private heroesURL = 'api/heroes';
      constructor(private http: HttpClient) { }
    
      getHeroes() : Observable<Hero[]>
      {
        return this.http.get<Hero[]>(this.heroesURL);
      }
    }
    
    hero.ts:[enter image description here][1]
    export interface Hero {
        id: number;
        name: string;
    }

2

There are 2 best solutions below

0
Pavan Jadda On

The issue was with @angular-devkit and @angular/cli incompatible versions. Strange that it works in StackBlitz. Anyway I forked and updated the demo.

StackBlitz: https://stackblitz.com/edit/stackblitz-starters-5f2abx

This works in local now.

0
Саша Ванюта On

I changed this by removing importProvidersFrom(HttpClientModule) from the providers list in my code configuration. This adjustment is depicted in the screenshot below:

Screenshot of the code change