Reputation: 11153
I've post method at my angular service say AuthService.ts
like this
@Injectable({
providedIn: 'root'
})
export class AuthService {
...
...
login(username: string, password: string) {
let headers = new Headers(); //1
headers.append('username', username); //2
let options = {
headers: headers
}; //3
return this.http.post < any > (`${environment.authBaseUrl}`, {
username,
password
}, options) //4
.pipe(map(user => {
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
}
}
My purpose is to add the username at the POST request header. Cause there in the API it is expecting that a username will be found at the request header. With the help of this post in StackOverflow, I'm trying to add the header (from comment 1 to 4). I'm getting the below error message -
TS2345: Argument of type '{ headers: Headers; }' 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'.
If I remove the option
from the post method then everything works fine.
Can anyone help me with this?
Thanks in advance
Upvotes: 1
Views: 2821
Reputation: 5111
Use HttpHeaders
instead of Headers
,
import { HttpHeaders } from '@angular/common/http';
let options = {
headers: new HttpHeaders({ 'username': username })
}
Upvotes: 2
Reputation: 986
Consider using HttpHeaders
.
For example:
(I just put application/json
content-type header for example purpose).
import { HttpHeaders } from '@angular/common/http';
[...]
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json', 'username': username)
};
[...]
return this.http.post<any>(`${environment.authBaseUrl}`, { username, password }, httpOptions) //4
.pipe(map(user => {
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
Upvotes: 2