How do I receive data form the API with key and header in angular 8

Viewed 299

I am trying to get data from the API with key and header format but didn't understand how to do this. when there is no header we receive data using the get method in service.

this is api.service.ts file:

export class ApiService {
  API_KEY = 'key......';

getData(){
    return this.httpClient.get(`https://data.org/v2/somethig=ng?sources=sdfgghhhh&apiKey=${this.API_KEY}`);
  }
1 Answers

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

Related