DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Julie Gladden
Julie Gladden

Posted on

HttpClient 'GET' - Angular Simplified

Hey, friends.

Today I want to break down Angular's method of calling APIs. I'll be doing an article for each CRUD operation, so keep your eye out and make sure to follow!
This is the basics, and you can find more info on Angular's website. I won't get into the nitty gritty of why and how things work here. As a beginner, sometimes too much information is a bad thing. So let's start simple and grow from there!

Step 1:

Time to import!

In your app.module file...

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule, <-- add to imports here
  ],
Enter fullscreen mode Exit fullscreen mode

In your .ts file...

import { HttpClient } from '@angular/common/http';
Enter fullscreen mode Exit fullscreen mode

Step 2:

Next we need to add to our constructor.

In your .ts file...

constructor(private http: HttpClient) {}
Enter fullscreen mode Exit fullscreen mode

Step 3:

Now it's time to call our API!

Here's our main functionality. Inside of the get parenthesis, we are going to put our URL or anything that needs to be sent over. Consider subscribe to be what actually plugs us in to the service. If you don't have it, we won't have the power to turn this function on. It'll give us back the data we need so we can use it elsewhere.

functionName() {
 this.http.get().subscribe()
}
Enter fullscreen mode Exit fullscreen mode

Now add your URL to it.

myUrl = 'https://www.heythisiscool.com/1'
functionName() {
 this.http.get(myUrl).subscribe()
}
Enter fullscreen mode Exit fullscreen mode

Next, you can do stuff in your subscribe parenthesis. You could console.log to see what you get back.

functionName() {
 this.http.get(myUrl).subscribe(data => {console.log(data)}
}
Enter fullscreen mode Exit fullscreen mode

Or you can put data in a variable.

myVariable;

functionName() {
 this.http.get(myUrl).subscribe(data => {myVariable = data})
}
Enter fullscreen mode Exit fullscreen mode

You can also do multiple things on subscribe. These things won't happen until the call is complete, so it's handy in many situations.

myVariable;

functionName() {
this.http.get(myUrl).subscribe(data => {
  myVariable = data,
  console.log(data),
  callAnotherFunction(),
  setAVariable = true
  }
}
Enter fullscreen mode Exit fullscreen mode

There's many other things to cover with get requests, so many sure to follow for the nitty gritty in the future!

Best wishes,
Julie

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.