Create Service
In this step of this tutorial, we will create a service that will consume the API route that we have defined in the backend such that we retrieve the list of the books. We will then modify our list-book component so that the list of books is displayed.
This process is somehow a little bit similar to the backend part, we start first by creating a book model. In the "src/app/shared/models" we create a new file "book.model.ts" and we add the following code:
export interface Book {
_id: string;
Title: string;
Author: string;
ISBN: string;
}Also we add the following line in "index.ts" that is in "src/app/shared/models".
export * from "./book.model"Now, through the console we navigate to the following path:
src/app/shared/services/and we type in the console:
ng generate service bmsWe now need to consume the API route that we have created in the backend. To do so, we modify the "bms.service.ts" file to the following:
import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs';
import {Book} from '../models/book.model'
@Injectable({
providedIn: 'root'
})
export class BmsService {
constructor(private httpClient: HttpClient) { }
getBooks(): Observable<Book[]> {
return this.httpClient.get<Book[]>("http://localhost:3000/api/user/getBooks");
}
}We need to check to add in our index.ts that is in "src/app/shared/services".
Last updated
Was this helpful?