My local variable is not being bound properly when retrieving data from a subscription.
In my setup, I have two components and a service. The parent component triggers a method in the service to make an HTTP GET request, which includes a user object that needs to be bound. However, when I try to access the object outside the subscription, it shows up as undefined.
Below is the code snippet:
Parent Component:
selectedUser : User;
onUserRowSelect(event): void {
this.router.navigate(['../childComponent'], { relativeTo: this.route });
this.formService.getUser(event.data.USER_ID).subscribe(result => {
console.log(result); // successfully logs the object.
this.selectedUser = result; // Assigning the local @Input variable to the result
});
}
Child Component:
@Input() selectedUser : User;
ngOnInit() {
console.log(this.selectedUser); // Returns undefined.
}
Service with HTTP:
getUser(id: number): Observable<User> {
const _url = 'myURL/getuser/' + id;
const headers = new Headers();
headers.append('X-User', sessionStorage.getItem('username'));
headers.append('X-Token', sessionStorage.getItem('token'));
headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
return this.http.get(_url, options)
.map(response => {
const responseAsObject = response.json();
this.myUser = responseAsObject;
return responseAsObject;
});
}
Even after using the @Input decorator for the variable, the child component still receives selectedUser as undefined. This is the issue I am facing.