Anyone try using InMemoryWebAPI with standalone components?
Asked Answered
G

1

12

I am using Angular v16 with standalone components. I implemented InMemoryWebAPI as I have in NgModule-based projects, but it doesn't seem to be working. I keep getting 404 not found.

Anyone try this and have success with InMemoryWebAPI with standalone bootstrapping? Anything else different I need to do to get it to work with standalone components?

Here is my app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    importProvidersFrom(InMemoryWebApiModule.forRoot(AppData, { delay: 1000 })),
    provideHttpClient(),
    provideRouter(routes, withComponentInputBinding())
  ]
};

Here is my AppData

export class AppData implements InMemoryDbService {

  createDb(): { products: Product[] } {
    const products = ProductData.products;
    console.log(products);
    return { products };
  }

}

And here is my service:

  private sub = this.#http.get<Product[]>('api/products')

Thanks for any ideas or debugging tips.

EDIT: I have a stackblitz here: https://stackblitz.com/edit/github-crud-signals-djk

The service currently has the http calls commented out because they were generating 404 errors. It instead hard-codes the data.

Glazing answered 7/6, 2023 at 21:53 Comment(0)
G
17

With assistance from the Angular team, I was able to resolve the issue. If you run into this, the solution was to adjust the order of the imports in the bootstrapping. They should look like this:

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    importProvidersFrom(InMemoryWebApiModule.forRoot(AppData, { delay: 1000 })),
    provideRouter(routes, withComponentInputBinding())
  ]
};

Notice that the HttpClient() is imported before InMemoryWebApiModule.

Glazing answered 16/6, 2023 at 18:47 Comment(2)
Thanks this helped but I wanted to know what is the { delay: 1000 } added for?Obvert
Since this "fakes" HTTP requests, it can be almost immediate to receive the response, which isn't very "real world". The delay is to make the HTTP responses more closely resemble actual responses. So I delay 1 second (1000 ms). You can adjust the amount as needed to mimic your backend server response time.Glazing

© 2022 - 2024 — McMap. All rights reserved.