⚡How to fetch Data from API in Angular 17 using Service | Fetch data from API in Angular |Angular 17

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello guys welcome to my YouTube channel if you are new to my Channel please subscribe to my channel like this video and press the Bell icon in this video I will show you how to fetch data from an API in angular 17 using service before proceeding I assume that you have a basic knowledge of angular I have already installed angular 17 if you want to know how to install angular 17 press the I button and watch the video open app. component. HTML file remove this code Type angular in H3 tag open a new terminal in your editor click here and select command prompt to open command prompt in your terminal now type the command and G serve to run your app open your browser and type Local Host colon 4200 you will see the text angular is displaying we will use a free API called Json placeholder to fetch the data in Google type Json placeholder and press enter click on this link to open the website click on the posts link under resources here you will see post data such as user id id title and Body in Json format we will fetch this data in our angular app copy this URL we will use this URL to fetch the posts click here and select command prompt to open a new command prompt in your terminal type the command NG space generate space component space post and press enter we will use this component to display post data open post. component.ts file we will use HTTP client module to fetch the post data we will use the inject function to inject the HTTP client module which was introduced in angular 14 type HTTP equals inject function and provide HTTP client inside the inject function make sure to import HTTP client and inject add a property name posts of type any and initialize it with an empty array we will use NG on a nit life cycle hook to fetch the posts so add implements on a knit and import on a nit from angular SL core now add NG on AIT method meod Define a function named fetch posts in this function we will use get HTTP request to retrieve posts from the API copy this API URL and add into the parenthesis next now subscribe to it and log the fetched posts to the console using console.log posts in the Subscribe function there is a call back function that will be executed when the HTTP request is successful the parameter posts any indicates that the type of the received posts can be anything providing flexibility in handling the data now let's log the fetched posts to the console using console.log posts Now call fetch posts inside NG on a nit life cycle hook add app post selector in app. component. HTML file you can see an error appst is not a known element we are using Standalone component so we need to add post component in the Imports array and import it in the app component.ts file open your browser and you will see an error in console null injector error no provider for HTTP client to fix this open app.config .ts file add provide HTTP client in the provider's array and import it from angular common HTTP the provide HTTP client configures angular's HTTP client service to be available for injection open your browser and you will see that the error is is gone and you can see the posts in the console the post contains body ID title and user ID there are total 100 posts now to display the posts in the HTML file assign the posts fetched from the API to a property named posts open postc component. HTML file we will use for Loop to display the posts the at4 block requires a track expression angular uses the value of this expression as a unique identity for each item first we will display post ID after that we will display post title and post body now open your browser and you will see all the posts open index.html file and add Tailwind CSS CDN in body tag add Tailwind CSS Class for Dark mode open post. component.ts file in the fetch post function append underscore limit equals 10 in the URL to display only 10 posts in post. component. HTML file I have added Tailwind CSS template to display the posts in a table here is the at4 block I have added empty block which will be displayed if there are no posts now open your browser and you will see the posts in a table now let's create Post Service to display the data in your terminal type the command NG G space generate space service space servicespost a service can be reused across multiple components this is beneficial when multiple components need to access the same data or when the same data retrieval logic is required in different parts of the application open post. serv. TS file declare a constant variable named basore URL and assign it the string value of the API URL in this case declare a private property named HTTP and provide HTTP client inside the inject function make sure to import inject and HTTP client now create a function named get posts and in this function return this. http.get in parentheses add basore URL open post. component.ts file comment this code create a private property named post service and provide post service inside the inject function make sure to import inject and post service comment fetch posts function create a function named load posts in this function we will use the post service property to call the get posts method from the post service now subscribe to it and log the fetched posts to the console using console.log posts in the Subscribe function there is a call back function that will be executed when the HTTP request is successful ful the parameter posts any indicates that the type of the received posts can be anything providing flexibility in handling the data now let's log the fetched posts to the console using console.log posts now to display the posts in the HTML file assign the posts fetched from the API to a property named posts Now call load posts function inside NG on a nit life hook now open your browser and you will see that all the 10 posts are displayed now let's implement the functionality to log an error if we encounter an issue with the API comment load posts function create a new load posts function in this function use the post service property to call the get posts method from the post service and subscribe to it the next call back will be executed when the request is successful it receiv receives the data in this case posts returned by the request assign the receive posts to a property named posts Now log a success message in the console the error call back will be executed when there is an error in the request Now log an error message to the console including details about the error now open your browser and you will see that all the 10 posts are displayed in console you will see the success message posts fetched successfully let's make some changes in the API UR URL to check if we see any errors in the console now if you open your browser no posts will be displayed and you will see an error in the console error fetching posts let's revert the changes made to the API URL now if you open your browser the post will be displayed and a success message will be shown in the console let's see in another example of fetching data from an API where we need an API key we will use tmdb API to fetch movie details in our app in Google type tmdb and press enter click on this link to open the website click on join tmdb enter your username password and an email to sign up you will need your username and password to login so save the details in a text file after that click on login and enter your username and password to log into your account now go to your account settings click on API and you will see your API key copy your API key and save it in a text file as we will need the API key let's create movie component and movie service in your terminal type the command NG space generate space component Space movie to create the movie component we will use this component to display movie details now type the command NG space generate space service space Services /m mov to create movie service type the command NG G space generate space environments to create environment file which will be used to store API key and URL open environment. TS file add a property named production and assign the value true this indicates whether our application is in production mode or not now let's add a property named API key and place your tmdb API key inside single quotes add the last property named API URL in the API URL enter this URL in single quotes https API doth movie.org 3discovery we will use this U Ur L to fetch movies from the movie DB API the API key will be used to authenticate the user for the movie DB API copy this code open environment. development. TS file and paste the code replace true with false for the production property open movie. service.ts file create a constant named API URL and assign it the value of environment. apiurl make sure to import environment now create another constant named API key and assign it the value of environment. API key both of these constants will be used to access API URL and API key from the environment file now create a private property named HTTP and include HTTP client inside the inject function make sure to import inject an HTTP client create a function named get movies in this function we will use get HTTP request to retrieve movies from the API in the parentheses add template literals then add dollar API URL in curly braces question mark API uncore key equals Dollar in curly braces API key in it this structure helps create a dynamic URL by inserting the values of API URL and API key into the string open movie. component.ts file create a private property named movie service and provide movie service inside the inject function make sure to import inject and movie service we will use NG on a knit life cycle hook to fetch the movies data so add implements on a knit and import on a knit from angular SL core now add a property movies of type any and initialize it with an empty array now add NG on a nit method it is a life cycle hook in that is called after the component has been initialized Define a function named load movies in this function use the movie service property to call the get movies method from the movie service and subscribe to it the next call back will be executed when the request is successful and it receives the response re s from the HTTP request now the movie service returns an object with a results property and it assigns the value of res. results to the components movies property now log the results to the console the error call back will be executed when there is an error in the request Now log an error message to the console including details about the error now we will call the load movies function inside NG on a nit life cycle hook open app. component. HTML file comment out the app post selector and add app movie selector you can see an error app movie is not a known element to fix this error open app component.ts file and add movie component in the Imports array and import movie component now open your browser and you will see the array of movies in the console each object in the array represents information about a movie and the structure of each object includes various properties related to that movie such as as backdrop path genre ID title and more open movie. component. HTML file add a d tag we will use for Loop to iterate over the array of movie objects and to display the details of each movie add movie.id to the track expression which will be used to uniquely identify each movie first we will display the poster of each movie using the poster uncore Path property here in the console you can see the poster underscore Path property now copy the original underscore title after the poster of each movie we will display the title of each movie add a tail in CSS class text Gray 100 for dark mode to the div now open your browser and you will see that the movie title is displayed but the movie poster is not showing in the com console you will see a 404 not found error for the movie poster image to fix this we need to use the base URL https image. tmdb orgt /p then you'll need a size let's say w500 then concatenate it with the poster under score path finally bind this expression to the SRC property of the IMG element now open your browser and you will see that movie title and movie posters are displayed in the movie. component. HTML file I have added a Tailwind CSS template to display both the movie title and the movie poster now if you open your browser you will see that four movies are displayed in a row open movie. component.ts file here you can see that we have used movies of type any while while using any provides flexibility it comes at the cost of reduced type safety you won't get compile time type checking for operations involving the movie's property for better type safety and code readability it's often recommended to use interfaces or types instead of any especially when dealing with structured data like arrays of objects in this context it would be beneficial to create an interface let's say movie detail which defines the expected structure of movie objects in your terminal type the command NG space generate space interface space interfaces / movie detail this command will create movie detail. TS interface file in app / interfaces folder this interface will specify the expected properties and their types for an object representing detailed information about a movie open your browser we need to convert the Json object into typescript interface for converting a Json object into a typescript interface we will use a vs code extension named Json to TS open movie detail interface and remove this code open your browser right click and click on copy object press and hold Control Plus shift plus alt plus v you can see that the typescript interface is created with movie properties and their types rename the interface to movie detail and Export it using the export keyword you can also use the transform tools website to convert a Json object into a typescript interface in Google type TS to Json and press enter click on this link right click and click on copy object remove this code and paste the copied object you can see that the typescript interface is created with movie properties and their types open movie. service.ts file in the get movies method include an observable of type movie detail and make sure to import both observable from rxjs and the movie detail interface now include the movie detail interface in the get method which expects a responsive type movie detail open movie. component.ts file declare a property movies as an array of type movie detail and initialize it with an empty array now in the load movies function include a type assertion as movie detail with res. results this assumes that res. results contains an array of objects conforming to the movie detail interface make sure to import movie detail interface open movie. component. HTML file remove original underscore title and now if you add a dot it will display all the properties of the movie detail interface it provides a clear and concise way to discover and work with the available properties of the movie detail interface open your browser and you can see that all the movie details are displayed without any error open movie. component. HTML file here we have concatenated the URL for the poster path using angular's property binding we will add this URL to the environment file and assign it to a property named IMG URL copy this URL open environment. development. TS file add a property named IMG URL and paste the copied URL into it copy this property open environment. TS file and paste the code here open movie. component.ts file create a constant named IMG URL and assign the value of environment. IMG URL to it ensure that you import the environment. TS file now create a function named get full image URL that takes a poster path parameter and returns a string representing the full URL for an image open movie. component. HTML file replace the current URL with the result of the get full image URL function passing movie. postore paath as an argument open your browser and you can see that all the movie details are displayed without any error thanks for watching please like share and subscribe to my channel I will see you in next tutorial till then stay safe
Info
Channel: Php Node Tuts
Views: 8,331
Rating: undefined out of 5
Keywords: angular 17, angular 17 tutorial, angular 17 project, How to fetch Data from API in Angular, How to fetch data from API in Angular 17, Angular Service, Angular Service tutorial, Fetch Data from API in Angular, Fetch Data from API in Angular 17, Angular 17 Course, Angular 17 Tutorial for beginners, Angular 17 inject method, Angular Api Call Tutorial, Angular dependency injection, Angular 17 new features, Angular projects for beginners, Angular latest version tutorial, angular
Id: Sa8nVPzNWq4
Channel Id: undefined
Length: 36min 4sec (2164 seconds)
Published: Mon Jan 01 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.