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);
}
}