skip to Main Content

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


  1. I guess you are using localStorage which only accept string values, you can use JSON.stringify to convert the object to string and save it. When you want to read it, just use JSON.parse to convert the string to object and use it!

    ...
    if(token && user){
          this.userStorageService.saveToken(JSON.stringify(token));
          this.userStorageService.saveUser(JSON.stringify(user));
          return true;
    }
    ...
    
    Login or Signup to reply.
  2. Just as the error says, you’re most likely trying to assign an Object to a variable of type string which is not possible, but it is hard to be sure as you are not showing use the part of your code that is producio

    If you are trying to save the user object inside some kind of storage like the LocalStorage or the SessionStorage you most likely want to convert your object to a string using JSON.stringify

    this.userStorageService.saveUser(JSON.stringify(user));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search