I`m trying to access a URL with Basic Authentication.
The URL returns JSON data.
How can I add my username and password to this http request below?
private postsURL = "https://jsonExample/posts";
getPosts(): Observable<AObjects []>{
    return this.http.get<AObjects[]>(this.postsURL); 
}
                Refer to https://angular.io/guide/http or https://v6.angular.io/guide/http#adding-headers
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa('username:password')
  })
};
Then use the headers:
return this.http.get<AObjects[]>(this.postsURL, httpOptions); 
                        i don't know what you want to do exactly after getting authorized, but to get authorized using a simple call with basic authentication you need to do like this:
let authorizationData = 'Basic ' + btoa(username + ':' + password);
const headerOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': authorizationData
    })
};
this.http
    .get('{{url}}', { headers: headerOptions })
    .subscribe(
        data => { // json data
            console.log('Success: ', data);
        },
        error => {
            console.log('Error: ', error);
        });
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With