我正在尝试以 userId 作为参数发出 HTTP 获取请求,并使用 Angular 返回单个用户配置文件,但不断返回未定义的数据。我知道问题不在于我的后端服务器,因为 Postman 的相同 HTTP 获取请求 可以正常工作。 此外,我从我的 Angular HTTP 请求中得到了 这个异常 (后端是用 Java 编写的),但不是来自 Postman HTTP 请求。
profile.component.ts:
profile: Profile;
constructor(private profileService: ProfileService) {
}
ngOnInit() {
this.getProfile();
}
getProfile() {
this.profileService.getProfile("5e7bd87e05854a05cc0f6898").subscribe(
profile => this.profile = profile,
);
console.log( this.profile );
}
profile.service.ts:
getProfile(userId: string) {
let params = new HttpParams().set("id", userId);
console.log( "executing HTTP get" );
//return this.httpClient.get<any>( "http://localhost:8080/user", { params: params });
// I've tried this above method and the one below
return this.httpClient.get("http://localhost:8080/user", { params: params })
.pipe(
map((data: any) => {
const profile: Profile = new Profile( data.object.id,
data.object.username,
data.object.password,
data.object.fname,
data.object.lname,
data.object.email,
data.object.joined );
return profile;
})
);
}
console.log( this.profile )
就像在undefined
浏览器控制台中一样。我认为我使用subscribe
不正确。有人知道我在做什么错吗?
编辑:这是 来自浏览器控制台的错误截图。不确定它是否相关。