๐ธ Lab 20 - Connecting the frontend and backend
February 15, 2023 ยท View on GitHub
โฐ Estimated time: 5 minutes
๐ Learning outcomes:
- Configure the Angular app for production
๐๏ธโโ๏ธ Steps:
When we serve the Store and API locally, they work great, because of the configured proxy discussed in previous labs. The Store will think the API lives at the same address.
When deployed separately however, they do not yet know about each other. Let's configure a production URL for the API.
-
In
apps/store/src/environments/environment.prod.tschange it to:export const environment = { production: true, apiUrl: 'https://<your-fly-app-name>.fly.dev', };
-
In
apps/store/src/environments/environment.ts:export const environment = { production: false, apiUrl: '', };
-
In
apps/store/project.json:{ //... "targets": { //... "build": { //... "configurations": { "production": { //... // Add this property: "fileReplacements": [ { "replace": "apps/store/src/environments/environment.ts", "with": "apps/store/src/environments/environment.prod.ts" } ] } } } } }
-
In
apps/store/src/app/app.module.ts:import { environment } from '../environments/environment';- Add a new provider:
ts providers: [{ provide: 'baseUrl', useValue: environment.apiUrl }],
-
In
apps/store/src/app/app.component.ts, inject your new token:constructor(private http: HttpClient, @Inject('baseUrl') private baseUrl: string) {}Then use it:
games = this.http.get<Game[]>(`${this.baseUrl}/api/games`);
-
In
libs/store/feature-game-detail/src/lib/game-detail/game-detail.component.ts- Inject it in the constructor:
@Inject('baseUrl') private baseUrl: string - Use it:
this.http.get<Game>(`${this.baseUrl}/api/games/${id}`);
- Inject it in the constructor:
-
Build the Store for production and trigger a deployment
-
Go to your Surge deployment URL - you should now see the full app with all the games.