0

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;
         }
      }
Mellville
  • 1,027
  • 2
  • 18
  • 39
  • Where are you using the environment data? it doesn't look like it gets send with the request. Perhaps add it to the headers object? – Ric Oct 27 '17 at 15:21
  • Adding some values to the environments won't magically send the credentials as headers with your HTTP requests. You need to read the documentation of Http and send the appropriate headers. And you'll find theur value(s) in the environment. Note that Http is soon to be deprecated. You'd better learn how to use HttpClient. – JB Nizet Oct 27 '17 at 15:22
  • Done it @FRECIA, but still wont accept HttpHandler as provider... – Mellville Oct 27 '17 at 18:24
  • yes, it's 4.4.6.... – Mellville Oct 27 '17 at 19:00

2 Answers2

1

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);
      }
    }
Lucas
  • 9,871
  • 5
  • 42
  • 52
  • Thanks for the grat answer @FRECIA, but how can I generate an interceptor via cli? – Mellville Oct 27 '17 at 16:39
  • I've followed your instructions but I still have some issues: Ate interceptor.ts file `import { AuthService } from '../services/data.service';` I get red underline in AuthService At app.module i get this one underlined: import `{TokenInterceptor} from './interceptor/interceptor';` – Mellville Oct 27 '17 at 17:00
  • I still get the 401...I mean, the credentials are not being sent...isn't is their place? ` request = request.clone({ setHeaders: { key:"7Q0ZBC889M7WRGRM", secret:"N6BQK4Z8PZ1HYYT4" } });` – Mellville Oct 27 '17 at 17:23
  • I've edited my post with your solution @FRECIA, take a look, it doesnt compile this way because httpClient is not accepting json...I dont get it, many thanks, you're being great – Mellville Oct 27 '17 at 17:43
  • now it's complaining that I dont provide httpHandler, but if I do all the list, NgModule gets underlined... – Mellville Oct 27 '17 at 18:04
1

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
Mellville
  • 1,027
  • 2
  • 18
  • 39