Reputation: 1097
this is an edited post. I am trying this simple http
request from an API with basic auth (like user and pass) and a params object (bind to a form); I've read the docs, checked out several posts, but nothing seem to work; I always get a 401 as a response...
Can some give me a help? (i'm new at this)
This is what I've got:
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Http, Headers} from '@angular/http';
import {response} from '../../models/response';
import {HttpErrorResponse} from '@angular/common/http';
import {HttpHeaders} from '@angular/common/http';
@Component({
selector: 'app-testing',
templateUrl: './testing.component.html',
styleUrls: ['./testing.component.css']
})
export class TestingComponent implements OnInit {
//OPTIONS
selectedColor:string;
selectedFont:string;
selectedSize:string;
//INTERFACE
results: response;
params = {
"handwriting_id": "8X3WQ4D800B0",
"text": "",
"handwriting_size": "",
"handwriting_color": "",
}
constructor(private http: HttpClient) { }
ngOnInit() {
}
onSubmit(f){
console.log(this.params);
this.http.get<Response>('https://api.handwriting.io/render/png?' + this.params,{
headers: new HttpHeaders().set('7Q0ZBC889M7WRGRM','N6BQK4Z8PZ1HYYT4'),
}).subscribe(data => {
this.results = data['results'];
console.log(this.results);
},(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('An error occurred:', err.error.message);
} else {
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
});
}
//OPTIONS
changeFont(){
document.getElementById("output-text").style.fontFamily = this.selectedFont;
}
changeColor(){
document.getElementById("output-text").style.color = this.selectedColor;
}
changeSize(){
document.getElementById("output-text").style.fontSize = this.selectedSize;
}
}
Upvotes: 0
Views: 2619
Reputation: 10303
I dont know if I get how you are supposed to get your data to the service endpoint... but if you sent it with postman through headers, then you want to do it the right way, you should use angulars new feature, interceptors. This way you can provide a simple interceptor to your main app.module and use the new httpClient in your service ... this way the headers will be added automatically to every request done by the service.
Here is a simple walkthrough you should refactor for your case:
1) create interceptor:
import {Injectable} from '@angular/core';
import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class Interceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${YOUR_TOKEN}` <-- the API should expect a token here
}
});
return next.handle(request);
}
}
2) Provide interceptor in your main module (usually app.module.ts):
import {HTTP_INTERCEPTORS} from '@angular/common/http';
import {Interceptor} from './path/to/interceptor';
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [{provide: HTTP_INTERCEPTORS,useClass: Interceptor,multi: true}]
})
export class AppModule {}
3) Apply interceptor to your service with new HttpClient (angular 4.3):
import { HttpClient } from '@angular/common/http'; <-- IMPORTANT new httpClient
export class DataService {
constructor(public http:HttpClient) {
}
getPNG(){
return this.http.get('https://api.handwriting.io/render/png')
.map(res => res);
}
addHand(user){
return this.http.post('https://api.handwriting.io/render/png', user)
.map(res => res);
}
}
Upvotes: 1
Reputation: 1097
I found the solution thanks to this post. Here's the main difference:
After:
headers: new HttpHeaders().set('7Q0ZBC889M7WRGRM','N6BQK4Z8PZ1HYYT4'),
}).subscribe(data => {//etc
Now:
headers: new HttpHeaders().set('Authorization', 'Basic ' +
btoa('STRSKVENJVBD0JDS:4ZN6VD256FEBHSM1'))
}).subscribe(data =>//etc
Upvotes: 1