Connecting Angular to a Spring API

     Not long ago I wanted to learn Spring, so I built a simple API that managed data for a conference. Now I've been learning Angular and I wanted to build something that I could use as a front-end for that Spring API. I followed along with these fantastic videos, and ultimately ended up with something that looked identical to what she built, but I wanted to try and get the Sprint API I built connected to my front end. The Spring API can display Sessions for a conference, stored in a local Postgres database, and I wanted to make a front-end application to display that data. I was pressed for time, and only ended up showing the sessions available, but I'm excited that I now have these tools available so I can continue to practice both Angular and Spring.


    Getting the Angular site up was easy, and I borrowed some of the styling I found in the videos I watched. Once had a running site, showing off a fancy empty table, I was ready to show off some data. First I just threw some JSON in a list to prove the table would appropriately display my data, and it worked. Angular data-binding is relatively straightforward.
    Next I had to get some real data. I built a Session.ts file to contain my session interface. This allowed me to build a Session object out of the JSON I'd be getting from my API, and I like that Angular feels very object-oriented compared to React or React Native. Angular is picky with what it gets back from a get request, but it's actually pretty helpful. In React sometimes I would make a request only to be answered with ¯\_(ツ)_/¯ because it came back as a promise or Sanskrit characters or something. Angular has us tell our series of objects to come back as an Observable, which makes it much easier to start working with. 


    It's important to remember to add HttpClientModule to your list of imports in your app.module.ts file. Once I had my API call built, I flipped on my API and waited for sweet data to appear, but nothing happened. I checked the console; CORS error. Before I panicked I started Googling how to allow CORS in Spring, and before I knew it I had the one-line fix for my issue. I just had to add @CrossOrigin to the top of my controller, and suddenly I was overflowing with sweet sweet data



Comments

Popular posts from this blog

API's in C#

Using WebRTC to build a videophone in React and TypeScript

Reviewing WPF and MVVM