The parameter type '{ email: string; }' in NGXS does not accept arguments of type 'string'

Struggling to retrieve data from an API using ngxs with this.store.dispatch(new GetUser(userEmail)) Attempted to use the user id stored in local storage as a string and convert it to a number but encountered a similar error (Argument of type 'string' is not assignable to parameter of type '{ userId: number; }'). Now attempting to get a user by email as a string, facing the error Argument of type 'string' is not assignable to parameter of type '{ email: string; }' in NGXS.


import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { UserProfile } from 'src/app/core/interfaces/userProfile';
import { GetUser } from './state/profile.action';
import { ProfileState } from './state/profile.state';
import { UserService } from './user.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})

export class ProfileComponent implements OnInit {
  @Select(ProfileState.userProfile) userProfile$!: Observable<UserProfile>;

  constructor(private store:Store,private router:Router,private userService:UserService) { }
  ngOnInit() {
    this.getUser();
  }
  getUser() {
     let userEmail = localStorage.getItem('email') || '';
      this.store.dispatch(new GetUser(userEmail)).subscribe((data) => {
        this.router.navigate(['/profile']);
  });
      this.userService.getUser(userEmail).subscribe((response) => (
      console.log(response)
    ));
}
  }

This pertains to the state/action code:

  static readonly type = '[Profile] getUser';
  constructor(public payload: { email : string }) {}
}
export class ProfileStateModel {
  userProfile: UserProfile|undefined;
}

@State<ProfileStateModel>({
  name: 'profile',
  defaults: {
    userProfile:undefined,
  }
})
@Injectable()
export class ProfileState {
  profile!: UserProfile;

@Selector()
static userProfile(state: ProfileStateModel) {
  return state.userProfile;
}
constructor(private userService: UserService) {}

@Action(GetUser)
getUser(ctx: StateContext<ProfileStateModel>, action: GetUser ){
  const state = ctx.getState();
  return this.userService.getUser(action.payload.email).pipe(
      tap((profile) => {
        ctx.setState({
          ...state,
          userProfile:profile
        });
        ctx.dispatch(new GetUser(this.profile));
      })
    );
    }}

This relates to the class:

export class UserProfile {
  id!: number;
  username!: string ;
  password!: string ;
  email!:string;
  name!: string ;
  roles!: Roles;
  token!: string ;
  cart!:Cart;
}

And related service information:

@Injectable({
  providedIn: 'root'
})

export class UserService {
  constructor(private httpClient: HttpClient) { }

  private USER_PROFILE = 'http://localhost:8080/api/user/';

  getUser(email:string):Observable<UserProfile>{
    return this.httpClient.get<UserProfile>(this.USER_PROFILE +'userbyemail/'+ email);
  }
}

https://i.sstatic.net/GPOL6.png

Answer №1

Modify

data: { username : string }

Substitute

data: string

Currently, the requirement is to perform

RetrieveUser({username: userName})
in this manner

Answer №2

I'm not familiar with Ngxs, I am experienced in using Ngrx. However, you might want to consider attempting the following approach:

this.store.dispatch(new GetUser({ email: userEmail }));

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

What is the best way to search and sort a MatTable with special characters like accents and diacrit

I need to implement a name filtering functionality for a table, regardless of whether the user includes accents or not. For instance: If the user types "hydrogen", the result should display "Hydrôgen" from the table. I am using Angular 8.1.3 and Angula ...

the process of extracting data from a request body in Angular 2

After creating a URL for end-users to access, I wanted to retrieve data from the request body when they hit the URL from another module. The process involves fetching the data from the request body, passing it to my service, and then validating the respons ...

Can one bring in a JavaScript function using webpack?

I have a unique JS library called: say-my-greeting.js function SayMyGreeting (greeting) { alert(greeting); } Now I want to incorporate this function in another (.ts) file; special-class.ts import SayMyGreeting from './say-my-greeting.js' ex ...

Uncomplicating RxJs Operators: Decoding switchMap and combineLatest

I currently have the following RxJS subscription : combineLatest([obs1$, obs2$]) .pipe( filter(val=>!!val[0] && !!val[1]), // ensuring no null values on both observables switchMap(([val1, val2]) => combineLatest([of(v1), getObs3$( ...

Effectively Monitoring Angular Router Link Status

Is anyone else facing an issue with router link active not working correctly when navigating to a route with a different ID? The class is applied on the first navigation, but not on subsequent navigations. Any solutions? This is my HTML file: <div clas ...

Processing dates with NestJS

I am trying to format a date string in my NestJS API from 'YYYY-mm-dd' to 'dd-mm-YYYY', or even better, into a date object. Unfortunately, the NestJS framework does not seem to recognize when Angular sends a Date as well. Should I be se ...

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

One way to declare i18next specifically in React's App.tsx file is by following these

In my React App.tsx file, I am looking for a way to declare const { t } = useTranslation() only once. After that, I want to be able to use { t(trans.things) } in my components without having to declare const { t } = useTranslation() again each time. Is t ...

What is the process for passing information to a nested component structure with parent-child-child relationships?

I am facing an issue with three nested components (C1, C2, C3) where C2 is called within C1 and C3 is called within C2. My goal is to pass data from C1 to C3 using property binding. In the template of C1, I successfully bound a variable that I can access ...

Exploring the navigation hooks of Angular version 4

Imagine having two components each with their own unique URLs: /dashboard /profile Is there a way to trigger onEnterDashboard when the browser lands on /dashboard, and then have onLeaveDashboard execute when navigating from /dashboard to /profile, follo ...

The array is not being spliced in the DOM, however, it is being spliced in the console - Ionic 2+/Angular

My scenario involves a dynamic array filled with items and values. The goal is to remove an item from the view list when a user clicks a button on that particular item. I'm struggling to identify why this functionality isn't working as expected. ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

Is there a way to toggle the visibility of the angular material toolbar at regular intervals?

I'm currently experimenting with the CSS animation feature to display and conceal the angular material toolbar in this demonstration. Inside the application component, the hide attribute is toggled at intervals as shown below: hide:boolean = false ...

What causes the discrepancies in versions of dependencies listed in the package-lock.json file?

Currently, I am developing an application using angular 10. I have noticed that the version of a dependency in my package-lock.json file is different from what I specified in my package.json after running the command: npm install. For example: In my pack ...

Avoid inheriting Parent component styles in Child component

I am facing an issue with styling a child component independently from its parent. Specifically, I want to prevent the text alignment set in the parent component from affecting the child component. Despite trying different ViewEncapsulation types (Native, ...

Typegoose's representation of modifying data

Recently, I delved into the world of NestJS and kickstarted a sample project. To integrate MongoDB seamlessly, I opted for Typegoose. A useful online tutorial () caught my eye, illustrating how to employ abstractions with base typegoose models. Hence, my ...

Disabling aria-label enforcement for icon-buttons in Chakra UI Typescript

Having a Chakra UI icon button, I am facing an issue with the aria-label attribute. The IconButton is within an aria-hidden section in the tree; therefore, the label becomes redundant. If I try to remove the aria-label, TypeScript throws complaints as sho ...

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...

The ngmodel variable is not responding to dynamic changes

I'm currently working on dynamically changing a date and getting it to reflect in the view, but for some reason it's not showing up. When the date is hard-coded in an array like this, it works perfectly fine and shows up in the view. My date : Ar ...