Injecting ApiService in Your Component
Next, open the src/app/news/news.component.ts, or component you want to use getNews() method, file and start by importing ApiService in your component:
import { ApiService } from '../api.service';
Next, you need to inject ApiService via the component's constructor:
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
constructor(private apiService: ApiService) { }
}
Sending the GET Request & Subscribing to The Observable
Next, define an articles variable and call the getNews() method of the API service in the ngOnInit() method of the component:
export class NewsComponent implements OnInit {
articles;
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.getNews().subscribe((data)=>{
console.log(data);
this.articles = data['articles'];
});
}
}
This will make sure our data is fetched once the component is loaded.
We call the getNews() method and subscribe to the returned Observable which will send a GET request to the news endpoint.
Displaying Data in The Template with NgFor
Let’s now display the news articles in our component template. Open the src/app/news.component.html file and update it as follows:
{{article.title}}
<p>
{{article.description}}
</p>
<a href="{{article.url}}">Read full article</a>
Resources: getting angular, rest api