SOLVED I am trouble with a TypeScript error


#1

Hey, I need help for a typescript error.

I am developing a login page and I try use an api for this authentication.

So I created a requestoptions object;

var requestOptions = new RequestOptions({headers:headers});

then I used that in a http.post() method

return this.http.post(url,JSON.stringify({username,password}),requestOptions)

And It turned an error, here it is

Typescript Error
Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'. Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'. Index signature is missing in type 'Headers'.

Thank you


#2

where are you defining this?

The error message says that there is the problem - when you don’t read it already I would highly recommend doing that.:smirk:


#3

Hello here is the defining;

let headers = new Headers();

headers.append("Authorization",btoa(username+":"+password));

var requestOptions = new RequestOptions({headers:headers});

Thanks for your reply


#4

Try the ‘HttpClient’ instead, i think you are using the deprecated old method with the new headers.
https://angular.io/api/common/http/HttpClient


#5
constructor(@Inject('apiUrl') private apiUrl, public http: HttpClient) { }

If I understood you correctly, you recommend use it this way?


#6

please try it, i have not tested it, but its worth a try,


#7

This is the current constructor method already :slight_smile:


#8

Sorry I meant HttpHeaders instead of header, I confused it with the httpclient.

You should use HttpClient and Http header.


#9

I tried that :confused: it doesn’t work. I created a topic in stackoverflow. You can see updates from here :slight_smile:


#10

looks like it got solved there, could you also report the solution for future reference here and mark the topic as solved?


#11

It solved by without using requestOptions, just used headers on post method

let headers = new HttpHeaders();

headers.append("Authorization",btoa(username+":"+password));

Use that values in that

return this.http.post(url,JSON.stringify({username,password}), { headers: headers })

But now I have StaticInjectorError[HttpClient] runtime error, so it’s not fully solved yet


#12

add ‘HttpModule’ to your app.module.ts

import { HttpModule } from '@angular/http'; 
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    HttpModule,
    ...

#13

I already did it, thanks for your reply it’s worked