๐Ÿ’ป Lab 8 - Displaying a full game in the routed game-detail component

October 16, 2022 ยท View on GitHub

โฐ Estimated time: 15-20 minutes

Now we have a proper API that we can use to make HTTP requests. We'll look at how the Nrwl NestJS generators created a helpful proxy configuration for us.

๐Ÿ“š Learning outcomes:

  • Learn how to connect frontend and backend apps in an Nx workspace


๐Ÿ“ฒ After this workshop, you should have:

App screenshot screenshot of lab8 result

๐Ÿ‹๏ธโ€โ™€๏ธ Steps:

  1. Import the HttpClientModule in apps/store/src/app/app.module.ts and add it to the module's imports array:

    ๐Ÿณ Hint
    import { HttpClientModule } from '@angular/common/http';
    

  2. Within the same folder, inject the HttpClient in the app.component.ts's constructor and call your new API as an HTTP request

    โš ๏ธ Notice how we assume it will be available at /api (more on that below)

  3. Because our list of games is now an Observable, we need to add an async pipe in the template that gets the games:

    ๐Ÿณ Hint
    <mat-card
      class="game-card"
      *ngFor="let game of games | async" <--HERE
      [routerLink]="['/game', game.id]"
      >...</mat-card
    >
    

  4. Run nx serve api

    โš ๏ธ Notice the PORT number

  5. In a different tab, run nx serve store

    โš ๏ธ Again, notice the PORT number

  6. Everything should still look/function the same!

    ๐ŸŽ“ You can inspect your Network tab in the dev tools and notice an XHR request made to http://localhost:4200/api/games


๐ŸŽ“ Even though the frontend and server are being exposed at different ports, we can call /api from the frontend store because Nx created a proxy configuration for us (see apps/store/proxy.conf.json) so any calls to /api are being routed to the correct address/port where the API is running. This helps you avoid CORS issues while developing locally.


Now let's load the full game in our routed component!

  1. Inside the libs/store/feature-game-detail/src/lib folder, replace the following files:

    โš ๏ธ Notice how we're using the shared formatRating() function in our routed component as well!

  2. You should now see a fully-fleshed out detail component when you link on the card list at the top! (you might need to restart your nx serve store so the new button styles can be copied over)

  3. Inspect what changed from the last time you committed, then commit your changes


๐ŸŽ“If you get stuck, check out the solution


โžก๏ธ Next lab โžก๏ธ