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
],
In your .ts file...
import { HttpClient } from '@angular/common/http';
Step 2:
Next we need to add to our constructor.
In your .ts file...
constructor(private http: HttpClient) {}
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()
}
Now add your URL to it.
myUrl = 'https://www.heythisiscool.com/1'
functionName() {
this.http.get(myUrl).subscribe()
}
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)}
}
Or you can put data in a variable.
myVariable;
functionName() {
this.http.get(myUrl).subscribe(data => {myVariable = data})
}
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
}
}
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)