Jamstack Explorers

Angular Dynamic Data with Sanity.io with Tara Z. Manicsic

Connecting Netlify Functions to an Angular Service

To use the data we're getting from the Netlify Function we need to make a service in Angular using the ng generate service command and our smart, smart brains.

📓 Resources 📓


[00:00:00] We'll make a service in Angular to use the data that we're grabbing and also make the model of what we're pulling in, which is the product. To start out we'll actually take advantage of the angular CLI and use the generate command ng generate service, call it, we'll put it in a services folder and call it products, super handy. Got that all setup. Then we can go into code and actually products.service.ts to start working on the [00:00:30] TypeScript file of this as service.

First, we're going to import that HTTP client that we added to the project and also import observable from our rxjs because what we're going to be pulling in will be observable. We also need to import product from the model, which we'll create. Next, we go ahead and use dependency injection to put in the HTTP inside of our constructors so that we can use that HTTP client.

Then we're going to do the get products function, and we're going--[00:01:00] we know we're going to be getting back an array of products, which is an observable and we'll return this.http.get, throw in that product array there. Then we're going to say .netlify/function/getProducts, which is where our function that's getting this data lives. Then we'll set headers as an object and just put in the content type, which should equal application/json. [00:01:30] That's everything we need in that file. We can save that out, head back to our terminal, change the directory to src/app. Then in here we're going to make a directory called models. This is where all of our models will live.

We just need to make a go into models and then make a file called product.ts. This is where we're going to make our strongly typed model of the product. I just went back to the [00:02:00] root directory and now we'll actually go back into our code editor and open up product.ts. In here we're going to export an interface of product and we're going to set these variables, they're all strings, we have ID, name, price, URL, image, and description.

A strongly typed interface of strings for our product. Now that exists [00:02:30] and tied to the service, let's go ahead and add all of the files that we changed and make a commit that says that it added HTTP, the product model, and the service. We will push that up and we've got data.

[00:02:44][END OF AUDIO]


your progress