-1

while getting data from Bing Api using POSTMAN works fine.

but the same in angular not works, problem is in sending headers.

Error Response: 401 (Access Denied)

what am doing wrong here

import { HttpClient, HttpHeaders } from '@angular/common/http';

   export class BingSearchComponent implements OnInit {

   constructor(private http: HttpClient) { }

   doSearch(input) {
   console.log(input.value)
   let subscriptionKey = 'XXXXXXXX';
   let customConfigId = 'XXXXXXXX';
   let searchTerm = 'microsoft';

   let headers = new HttpHeaders();
   let other_header = 
      headers.append('Ocp-Apim-Subscription-Key','XXXXXXXX'); //prints correctly here

   console.log(other_header.get('Ocp-Apim-Subscription-Key'))
   let url = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?'
   + 'q=' + searchTerm + '&customconfig=' + customConfigId

    this.http.get(url, {headers: other_header}).subscribe(
      res => console.log('handle your response', res),
      msg => console.error(`Error: ${msg.status} ${msg.statusText}`)
    );
  }
 }
codedamn
  • 811
  • 4
  • 10
  • 16

2 Answers2

0

HttpHeaders() is an immutable list.

And at this point: this.http.get(url, {headers: headers})

headers has only been set to new HttpHeaders();

Did you mean to put other_header instead of headers?

CHAZTATS
  • 114
  • 8
  • Yes but because it's an immutable list you're actually setting other_header to be your whole headers object. You should change other_header to headers. `let headers = new HttpHeaders(); headers = headers.append(...);` then remove other_header entirely. – CHAZTATS Feb 27 '18 at 12:38
  • tried this one also not works "let headers = new HttpHeaders({'Ocp-Apim-Subscription-Key':'XXX');" – codedamn Feb 27 '18 at 12:42
  • 400 (Bad Request) – codedamn Feb 27 '18 at 12:43
  • could you log out the whole headers object after my implementation and see what it produces? – CHAZTATS Feb 27 '18 at 12:46
0

HttpHeader calss's instances are immutable as a result invoking its methods will return a new instance.

you should give this a try instead, (passing all the headers as an object)

http.get('someurl',{headers: {'Ocp-Apim-Subscription-Key':'XXXXXXXX'}});
manish
  • 1,450
  • 8
  • 13