When using Angular, it is important to remember that calling `this.useraccount.next(user)` may result in an error stating that an argument of type 'HttpResponse<any>' cannot be used with a 'Useraccount' balance

When attempting to use this.useraccountsubject(user) to insert information upon login, I encountered an error:

ErrorType: this.useraccount.next(user) then Error An argument of type 'HttpResponse' is not allowed against a balance of 'Useraccount'

Here is the code snippet from auth service.ts:

export class AuthService {
  
  private useraccountSubject: BehaviorSubject<Useraccount> =
  new BehaviorSubject<Useraccount>(new Useraccount("", "", "", "", ""));
  public user: Observable<Useraccount> = 
   this.useraccountSubject.asObservable();
   isLoggedIn = new BehaviorSubject(false);

   constructor(private http:HttpClient, private router:Router){
      this.useraccountSubject = 
            new BehaviorSubject<Useraccount>(null as any);

      this.user = this.useraccountSubject.asObservable();

      if(sessionStorage.getItem("USER")){ 

        const user =sessionStorage.getItem("USER");

      if(user){
        this.useraccountSubject.next(JSON.parse(user));
      }

     }

   }

   private handleError(err: HttpErrorResponse) {

     if (err.status === 200) {
        console.error('Error:',err.error.data)
     } else {
        console.error(`Backend error ${err.status}`)
     }

     return throwError(err);
   }

   private handleErrorsingup(err: HttpErrorResponse) {
     if (err.status === 201) {
       console.error('Error:',err.error.data)
     } else {
       alert('faild');
       console.error(`Backend error ${err.status}`)
     }

     return throwError(err);
   }

   login(username:string,password:string){ 
      const params = new FormData();
      params.append('username', username);
      params.append('password', password);

      return this.http.post<any>(`${baseUrl}/signin/`, params, { observe:'body', withCredentials: true})
    .pipe(map(user=>{
     
      catchError(this.handleError)

      //edit !!
      this.useraccountSubject.next(user);
      sessionStorage.setItem("USER", JSON.stringify(user));

      this.isLoggedIn.next(true);

      return user;
    }));
   }
     
   signup(email:string,password:string,name:string ){
     const params = new FormData();
     params.append('email', email);
     params.append('password', password);
     params.append('name', name);

    return this.http.post<any>(`${baseUrl}/signup/`, params, { observe:'body', withCredentials: true })
    .pipe(
      catchError(this.handleErrorsingup)
     );
   }
    

   logout(){
      return this.http.post<any>(`${baseUrl}/signout/`, {})
       .subscribe(response => {
          this.isLoggedIn.next(false);
          this.useraccountSubject.next(null as any)
          sessionStorage.clear();

          this.router.navigate(['login']) 
      })
   }

 //edit
 setUseraccount(user: Useraccount): void {
    this.useraccountSubject.next(user);
 }

 getUseraccount(): Observable<Useraccount> {
    return this.useraccountSubject;
 }
}

The 'HttpResponse' format does not match the attributes of id, username, name, password, and email in the 'Useraccount' format.

Here is the code snippet from Useraccount.ts:

export class Useraccount{
  constructor(
    public id:string,
    public username: string,
    public name: string,
    public password: string,
    public email: string
){}
}

It appears that the format for Useraccount.ts is available.

Additionally, here is the code snippet from header.ts:

export class HeaderComponent implements OnInit {
   private userSubject: BehaviorSubject<Useraccount> = new   
 BehaviorSubject<Useraccount>(new Useraccount("", "", "", "", ""));


   user:Observable<Useraccount> = this.userSubject.asObservable();

  loginStatus?: boolean;
  constructor(private authservice:AuthService) {



}

  ngOnInit(): void {

   this.authservice.getUseraccount().subscribe(res => {
  if (res === null) {

     // handler error

     console.log(this.user);
  } else {
   
    let useraccountSubject: Useraccount = new Useraccount(res.id, res.username, res.email, res.password, res.name);

     this.userSubject.next(useraccountSubject);
  }
});

   this.authservice.isLoggedIn.subscribe((status:any) => {
   this.loginStatus = status;
   });
 }
 logout($event: any){
$event.stopPropagation();
this.authservice.logout();
}
}

Here is the code snippet from header.html:

   <ul class="info_ul" *ngIf="!loginStatus" >
      <li><a  routerLink='/login' >login</a></li>
      <li><a routerLink='/singup' >signup</a></li>
  </ul>
  <ul class="info_ul" *ngIf="loginStatus">
    <div *ngIf="user | async"> //edit
     <li>{{( user | async).username }}</li> //username . string error
    </div>
    <li><a (click)="logout($event)">logout</a></li>
</ul>

Lastly, in the console:

user: {id: 7, uuid: '11a25078-be87-4a53-9ff7-ead8777f79be', username: 
'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7c5c5e7d3c2d4d389ccd5">[email protected]</a>', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8be9e9cbffeef8ffa5e0f9">[email protected]</a>', name: 'beom', …}
[[Prototype]]: Object

The error has been resolved, but the username is not being displayed in the header. Can you please assist with resolving this issue?

Answer №1

There may be an issue with the data types

Here are some adjustments you can make to your code

Firstly, update the User Class:

export class Useraccount {

   constructor(
        public id:string,
        public username: string,
        public name: string,
        public password: string,
        public email: string
   ){}
}

Update AuthService as follows:

private currentUser: BehaviorSubject<Useraccount> =
  new BehaviorSubject<Useraccount>(new Useraccount("", "", "", "", ""));

login(username:string,password:string){ 
      const params = new FormData();
      params.append('username', username);
      params.append('password', password);

      return this.http.post<any>(`${baseUrl}/signin/`, params, { observe:'body', withCredentials: true})
      .pipe(
         catchError(this.handleErrorsingup)
       );
}

logout(){
      return this.http.post<any>(`${baseUrl}/signout/`, {})
       .subscribe(response => {
          this.isLoggedIn.next(false);
          this.setCurrentUser(null);
          sessionStorage.clear();

          this.router.navigate(['login']) 
}

Add two new functions to the auth.service:


setCurrentUser(user: Useraccount): void {
   this.currentUser.next(user);
}

getCurrentUser(): Observable<Useraccount> {
   return this.currentUser;
}

Modify the header component with the following code:


export class HeaderComponent implements OnInit { 

  user: Useraccount = new Useraccount("", "", "", "", "");

  private userNameSubject: BehaviorSubject<string> = new BehaviorSubject<string>("");

  userName$: Observable<string> = this.userNameSubject.asObservable();

  loginStatus?: boolean;
  constructor(private authservice:AuthService) { }

 ngOnInit(): void {

   this.authservice.getCurrentUser().subscribe(res => {
      if (res === null) {
        
         // handle error

         console.log(this.user);
      } else {
        this.userNameSubject.next(res.username);

        this.user = new Useraccount(res.userId, res.username, ...);
      }
    })
   this.authservice.isLoggedIn.subscribe((status:any) => {
     this.loginStatus = status;
   });
 }

 logout($event: any){
   $event.stopPropagation();
   this.authservice.logout();
   this.user = new Useraccount("", "", "", "", "");
  }
}

<ul class="info_ul" *ngIf="!loginStatus" >
      <li><a  routerLink='/login' > Login </a></li>
      <li><a routerLink='/singup' > Sign Up </a></li>
</ul>
<ul class="info_ul" *ngIf="loginStatus">
    <ng-container>
    <li>{{ userName$ | async }}</li>
    </ng-container>
    <li><a (click)="logout($event)"> Logout </a></li>
</ul>

Answer №2

Unable to leave a comment at the moment, so I'll post my thoughts here.

It seems like there might be a type casting problem. In the upcoming method on BehaviorSubject, consider constructing a Useraccount object for your data like this:

this.useraccountSubject.next(new Useraccount(user));

By the way, if this approach doesn't yield results, consider using Useraccount as an Interface.

Answer №3

There seems to be an issue in the following line of code

this.http.post<any>(`${baseUrl}/signin/`, params, {observe:'response', withCredentials: true})

The observe parameter needs to be changed to body

this.http.post<Useraccount>(`${baseUrl}/signin/`, params, {observe:'body', withCredentials: true})

Refer to Overload #15 in the documentation provided here: https://angular.io/api/common/http/HttpClient#post

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery's making an error here - looks like matchExpr[type].exec is missing in action

Today, I encountered an error while running my code. Despite searching for guidance online, resources that could help me were hard to come by. Specifically, after crafting a few JavaScript functions, any attempt to use jQuery's methods on selectors r ...

The values returned by the Node.js API can vary for identical requests

I am currently learning how to use Node.js + Express in order to create a REST API. Within this API, I have implemented the following method: apiRouter.route('/training/session/byId/:id_session') // ===== GET ======= .get(function(req, res ...

If the if logic in Express.js fails to function properly, it will consistently output the same message

Every time I run this code, it always displays the same message, even when I input different email addresses let message = ""; const findQuery = "select email from Users where email = ?"; const queryResult = await db.query(findQue ...

Error in Next.js 11: Unable to access property 'canonicalBase' as it is undefined

Encountering an issue after upgrading from Next.js version 10.0.2 to 11.0.1. Since the update, I am unable to initiate a project due to the following error: Cannot read property 'canonicalBase' of undefined In my _app.tsx file, the Next imports ...

The ActionController is encountering an UnknownFormat error when trying to respond to AJAX requests with js using

I've been scouring the internet for information on this topic, but I'm having trouble understanding how AJAX works with Rails. I've gone through the documentation multiple times and it's just not clicking for me. From what I gather, AJ ...

What is the best way to refresh NGRX data?

There are two models in a one-to-many relationship: export interface GroupModel { id: number; name: string; userIds?: number[]; } export interface UserModel { id: number; name: string; groupId?: number; } An issue arises when updating either m ...

Struggling to pinpoint the exact element in Python/Selenium

As I work on creating a website manipulation script to automate the process of email mailbox creation on our hosted provider, I find myself navigating new territory in Python and web scripting. If something seems off or subpar in my script, it's beca ...

After a certain period of time, the NodeJs exec() function ceases to create additional

I am in the process of developing a BLE scan module on nodeJs using Bluez. Below is the code snippet I have implemented: exec('sudo hcitool lescan --duplicates &', function (error, stdout, stderr) { }); exec('sudo hcitool lescan --dupl ...

There is a potential for the object to be 'undefined' when calling the getItem method on the window's local storage

if (window?.sessionStorage?.getItem('accessToken')?.length > 0) { this.navigateToApplication(); } Encountering the following error: Object is possibly 'undefined'.ts(2532) Any suggestions on how to resolve this issue? I am attem ...

Deactivate certain days in Material UI calendar component within a React application

Currently, my DatePicker component in React js is utilizing material-ui v0.20.0. <Field name='appointmentDate' label="Select Date" component={this.renderDatePicker} /> renderDatePicker = ({ input, label, meta: { touched, error ...

troubles with compatibility between bootstrap.css and IE11

I am currently developing a web application using AngularJS and bootstrap.css. While everything appears fine on Chrome, I am facing some formatting issues on both Firefox and IE11. HEAD <head> <meta charset="utf-8"> <meta http-equi ...

When you hover over them, Material UI icons shrink in size due to the Border

I've been working on a React application that includes Material UI icons in the header. My goal is to add a border at the bottom of each icon when hovered over, but currently, the borders are too close to the icons. Another problem I'm facing is ...

Exploring methods for testing React components with TypeScript's props

I am currently tackling a react-typescript project and I am looking to conduct testing on props passed to a react component using react-testing library. Here, we have the SharedDashboardUiLatestValueWidget.tsx component: export interface SharedDashboardU ...

What are the benefits of using a combination of design patterns in JavaScript?

Currently, I am working on a personal project for learning purposes, which is a simple To-Do List. I am implementing the modular pattern (specifically, the revealing module pattern). The image below showcases my general idea of how I intend to build it. V ...

Using Node.js to establish communication between HTML and Express for exchanging data

I am faced with a challenge involving two pages, admin.hbs and gallery.hbs. The goal is to display the gallery page upon clicking a button on the admin page. The strategy involves extracting the ID of the div containing the button on the admin page using J ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

What are the steps to creating a duplicate of JotForm?

After exploring JotForm, I discovered it is an extremely interactive form builder utilizing the Prototype JS library. I am curious to know which JS framework or library would be a solid foundation for creating a similar form builder - JQuery, Prototype, ...

Unable to hide jQuery form and receiving undefined function output

I seem to be facing an issue with one of the buttons. It's not functioning properly. Whenever I click on the "Add Run" button followed by the "Home" button, most functions stop working as expected. The dynamically created form doesn't hide, the ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

Issue with the exported elements known as 'StatSyncFn'

My build is showing an error that I'm unable to identify the source or reason for. The error message looks like this... Error: node_modules/webpack-dev-middleware/types/index.d.ts:204:27 - error TS2694: Namespace '"fs"' has no expo ...