Making service call in Angular
Hi everyone .
This article is about handling network calls in angular , how to get get response and how to handle error.
If you don't have angular cli installed , you can create an angular project using code sand box.
To handle any service call , you have to import HttpClientModule.
Before making an service call , we should have an api ready . In this article we will be using a public api that gives us questions for quiz.
" https://opentdb.com/api.php?amount=10&type=multiple "
we will be using this api link to make service call.
understanding api call
Now that we are ready with httpModule and api link , we should inject http in our component file.
constructor(private http: HttpClient) {
}
Now we can make a get request on this api , that will give us quiz data
ngOnInit() {
this.http
.get(`https://opentdb.com/api.php?amount=10&type=multiple`)
.subscribe(
res => {
console.log("data:", res);
},
err => {
console.log("error:", err);
}
);
}
http returns an observable that can be subscribe to get response from api.
Subscribe has two parameters ,
-> first one is for response from api call , which in this case is written as res.
-> second parameter is for error , if any error occurs while making a service call , it can be handled here.
Comments
Post a Comment