I am configuring a login in Angular 17 in which I am using userStorageService but when I want to store the user there it generates this error
Argument of type ‘Object’ is not assignable to parameter of type ‘string’
this is my code
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, map } from 'rxjs';
import { UserStorageService } from '../storage/user-storage.service';
const BASIC_URL = "http://localhost:8080/"
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient,
private userStorageService: UserStorageService
) { }
register(signupRequest:any): Observable<any>{
return this.http.post(BASIC_URL+"sign-up", signupRequest);
}
login(username: string, password:string):any{
const headers = new HttpHeaders().set('Content-Type', 'application/json');
const body = {username, password};
return this.http.post(BASIC_URL + 'authenticate', body, {headers, observe: 'response'}).pipe(
map((res)=>{
const token = res.headers.get('authorization').substring(7);
const user = res.body;
if(token && user){
this.userStorageService.saveToken(token);
this.userStorageService.saveUser(user);
return true;
}
return false;
})
);
}
}
I have already checked the imports and everything but I don’t know what is wrong
2
Answers
I guess you are using
localStorage
which only accept string values, you can useJSON.stringify
to convert the object to string and save it. When you want to read it, just useJSON.parse
to convert the string to object and use it!Just as the error says, you’re most likely trying to assign an
Object
to a variable of typestring
which is not possible, but it is hard to be sure as you are not showing use the part of your code that is producioIf you are trying to save the
user
object inside some kind of storage like theLocalStorage
or theSessionStorage
you most likely want to convert your object to a string usingJSON.stringify