angularangular-in-memory-web-api

Angular In-memory-web-api not finding individual objects throws 404


I have an angular app which i am using the in-memory-web-api to mock up some http calls to a REST api that is not yet up and running.

I am trying to get some Podcast objects by hitting the following app-routing-module.ts setup:

const routes: Routes = [
    { path: 'podcast/:name', component: PodcastComponent }
];

In my component I call a getPodcast() method from the podcast-service like this:

getPodcast(name): void {
    this.podcastService.getPodcast(name).subscribe(Podcast => {
        this.podcast = Podcast;
        console.log("This.podcast = " + JSON.stringify(this.podcast));
        this.getEpisodes();
    });
}

The podcast service looks like this:

private podcastUrl = 'api/podcasts';

getPodcast(name): Observable<Podcast> {
    return this.http.get<Podcast>(`${this.podcastUrl}/${name}`);
}

And my in-memory-web-api looks like this:

    const podcasts = [
        { name: '@user1' },
        { name: '@user2' },
        { name: '@user3' }
    ];

    return {
        podcasts
    };
}

And I have a podcast Object defined as:

export class Podcast {
    name: string;
}

However when I try to get the Podcast it throws a 404 in the console:

ERROR {body: {…}, url: "api/podcasts/@user1", headers: HttpHeaders, status: 404, statusText: "Not Found"}

The URL looks good, so I don't know why it doesn't work.

Most weird is that if I get all the podcasts, it does work!

In the service I've got a method to get all podcasts:

getPodcasts(): Observable<Podcast[]> {
    return this.http.get<Podcast[]>(this.podcastUrl);
}

And then change the getPodcast() function in the component to call this:

getPodcast(name): void {
    this.podcastService.getPodcasts().subscribe(Podcasts => {
        Podcasts.forEach((podcast, i) => {
            if(podcast.name === name) this.podcast = podcast;
        });
    });
}

It then works perfectly. I am doing something totally stupid here? This is very odd behaviour... (I'm a newbie to Angular so be kind!)


Solution

  • Two things,

    first: `

    The in-memory web api library currently assumes that every collection has a primary key called id.

    `as stated here link description here

    Second: If you want to "get" something using something different from the "id" you have to use this sintax:

    GET api/heroes?name=^j //URL?PropertyName=Value
    

    Hope it helps