Rest Requests and Signals
Intro
In this lab we will start a new project that will connect to a back-end system using REST, and we will make our first get request.
1. Start the back end server
- clone and run the back end server with these commands:
git clone https://github.com/vppmatt/building-access-management-simulator.git
cd building-access-management-simulator
mvnw package
java -jar target\building-access-management-simulator-0.0.1-SNAPSHOT.jar
- check the back end is running by visiting this URL in your browser:
http://localhost:8080/swagger-ui/index.html
Note: In this project, you should only call end points that start with /api/ - all /api2/ endpoints have security enabled.
2. Create a new project
- Create a new project
ng new building-manager
-
Open the project in VSCode
-
Clear out the content of the app component's HTML.
-
Run the project
ng serve
3. Make a REST get request
- Add the provideHttpClient() method call to the providers list in app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes),
provideHttpClient()
]
};
- Create a new service
ng g s rest
- In the rest service inject the httpClient, then create a method that will make a get request to
http://localhost:8080/api/buildingto retrieve a list of buildings. You will first want to create an interface to store the object type.
Click here to see the sample solution
export interface Building {
id: number;
name: string;
}
export class RestService {
private httpClient = inject(HttpClient);
getBuildings() : Observable<Building[]> {
return this.httpClient.get<Building[]>('http://localhost:8080/api/building');
}
}
- In the App component, inject the restService, then in an ngOnInit function, call the getBuildings method, subscribe to the results and log them to the console
Click here to see the sample solution
private restService = inject(RestService);
ngOnInit(): void {
this.restService.getBuildings().subscribe(buildings => {
console.log('Buildings fetched on app init:', buildings);
});
}
- Test the application in the browser!
4. Use a signal to store the data
- In the app component define a class level variable as a signal of an array of buildings.
Click here to see the sample solution
buildings = signal<Building[]>([]);
- In the ngOnInit method, when the data is loaded, store it in the buildings variable rather than logging it to the console
Click here to see the sample solution
ngOnInit(): void {
this.restService.getBuildings().subscribe(data => {
this.buildings.set(data);
});
- Display the list of buildings as an unordered list in the HTML
Click here to see the sample solution
<h1>Buildings</h1>
<ul>
@for(building of buildings(); track $index) {
<li>
{{ building.name }}
</li>
}
</ul>
- Test the application in the browser!