【发布时间】:2021-09-08 10:13:27
【问题描述】:
我正在尝试使用 ngxs this.store.dispatch(new GetUser(userEmail)) 从 api 获取数据 我尝试通过从 localstorage 存储的用户 ID 作为字符串并将其转换为数字..我得到类似的错误('string' 类型的参数不可分配给'{ userId: number; }' 类型的参数)...现在我正在尝试通过电子邮件作为字符串获取用户...我收到错误 'string' 类型的参数不能分配给'{ email: string; 类型的参数。 }' 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)
));
}
}
这是状态/动作代码
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));
})
);
}}
这是课
export class UserProfile {
id!: number;
username!: string ;
password!: string ;
email!:string;
name!: string ;
roles!: Roles;
token!: string ;
cart!:Cart;
}
还有服务
@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);
}
}
【问题讨论】:
标签: angular typescript ngxs