After receiving data from a subscription, I am encountering an issue where my data is not binding to the local variable as expected.
The scenario involves two components and a service. The parent component triggers a method in the service to perform an HTTP get request, which includes a user object that needs to be bound. However, when logging the object outside of the subscription, it returns undefined.
Highlighted 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); // <-- Object is logged properly.
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;
});
}
HTML Form Templates:
Child template
<div id="top">
<nb-card>
<nb-card-header>Update User</nb-card-header>
<nb-card-body header="Update User">
... (omitted for brevity) ...
</form>
</div>
</div>
</nb-card-body>
</nb-card>
Parent HTML:
<div>
<div class="row-md-6">
<nb-card title="List of Users">
<ng2-smart-table [settings]="settings" [source]="source" (userRowSelect)="onUserRowSelect($event)"></ng2-smart-table>
</nb-card>
</div>
</div>
In summary, the parent component displays a list of users, while the child component serves as a form menu for editing the selected user. Despite adding the @Input decorator to the variable, the issue persists with the selectedUser appearing undefined in the child component.