I am trying to make an HTTP get request at takes a userId as a parameter and returns a single user profile using Angular, but keep getting undefined data returned. I know the problem isn't with my backend server because the same HTTP get request with Postman works correctly. Also, I am getting this exception (backend is written in Java) from my Angular HTTP request, but not from the Postman HTTP request.
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;
})
);
}
The console.log( this.profile )
just comes out as undefined
in the browser console. I think I'm using subscribe
incorrectly. Anyone know what I'm doing wrong?
EDIT: Here is a screenshot of the error from the browser console. Not sure if it's relevant.
The call
this.profileService.getProfile()
returns an Observable that isasync
. So the call flow is doing this:this.profileService.getProfile("5e7bd87e05854a05cc0f6898")
starts the HTTP requestconsole.log(this.profile)
gets called (It isundefined
because it hasn't been set yet).subscribe()
runs. (in your caseprofile => this.profile = profile,
)To fix your issue, just move your
console.log
into your.subscribe()
callback.I am not sure how that error is related because you haven't posted your
notifications.service.ts
code. It could be related to how you are setting the profile, but I cannot tell without seeing that other code. Same for the Java error. Not sure what the difference is between your Postman request and your Angular request.Fixing the
console.log
will solve yourundefined
error. Hopefully that will help you figure out the Java error. That Java error appears to be related to a Web Socket or something. Just taking a wild guess, but I doubt your HTTP call to fetch your user's profile is causing that error.