Hello everyone, welcome back to justlaravel.com! I am back with another tutorial, here am going to continue with the Laravel API series, wherein the previous tutorials detailed you creating an API in Laravel and integrating it with passport and also shown you how to consume the API another Laravel app and even in other frontend frameworks like Vue.js, and here I will show you how to consume our API in Angular app. So let us create our Angular consumer app.
Install Angular CLI
Angular comes with a beautiful CLI. So let me first install the Angular CLI and then create an angular app using the CLI. To install Angular CLI, run the following command.
Having Angular CLI installed, lets now create a new Angular app, run the following command to do so.
When the above command is executed, it asks for some options like routing and stylesheet format, actually, I don’t bother about those now as this is just a sample app to demonstrate how to consume a Laravel API so I opt No to routing and stylesheet format as CSS.
Angular Consumer App – Create a service for API
So here we can create a
service to make HTTP calls to the API and then we can
subscribe to the service to get the result from the API.
A service can be generated using Angular CLI by running the following command.
So now I will make calls to the API in the
users.service.ts using an Angular’s HttpClient. I can use the HttpClient by importing it from the Angular modules.
Now let’s modify the ‘UsersService’ constructor’s parameter, I will add the HttpClient which was just imported to it.
After that, I will create 2 methods in this service, one for getting the access token and another one for getting the users list.
Angular Consumer – Get authenticated with the API
So, now let me create a method in
users.service.ts for authenticating the API.
And I will subscribe to this service method in our main component file(app.component.ts).
Here in the above snippet, I have subscribed to the service
getAccess and store the
access_token we get from the result in a variable
access_token . So after getting the access token we can call another API endpoint to get the users list.
Angular Consumer – API call to get users
Let me create another method in
users.service.ts to get the list of users from the API. Here I will pass the access_token we got as a header to the call.
Now, in the main component, I will subscribe to this service.
In the above snippet, I have subscribed to the service
getUsers and stored the result in a variable
data holds all of the users retrieved from the API. Now, I will just loop it show the results in a basic HTML table.
Show the result(users)
In the app.component.html file, I will just loop
ngFor directive and display the users.