Data binding not being subscribed to the input decorator

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.

Answer №1

When your child component is initialized asynchronously, both the parent and child components will have selectedUser set to undefined if it has not been initialized yet. This is normal due to the asynchronous nature of the process. It may take some time for the response to be received. To monitor any changes to the @Input variable, you can utilize the OnChanges lifecycle hook. This hook is triggered whenever changes occur in the @Input variable. In your child component, you can add the following code:

ngOnChanges() {
  if (this.selectedUser) {
    console.log(this.selectedUser)
  }
}

Answer №2

To ensure that errors are properly handled in the HTTP GET method, the first step is to include a catch operator in the code. Within the catch block, you can implement logging functionality to capture any errors that may occur. If an error does occur, the associated variable will remain undefined.

return this.http.get(_url, options)
    .map(response => {
        const responseAsObject = response.json();
        this.myUser = responseAsObject;
        return responseAsObject;
    })
    .catch(error => log(error));

Once the catch operator has been added, it is recommended to open the browser console to monitor for any potential errors. If errors do arise, be sure to investigate the server for possible issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After a successful login, Angular will once again redirect the user to the login page

I successfully implemented the back-end using nest-js to handle authentication with mongo-db. Registration and login are working fine, but I face an issue after logging in with a successful result - when I refresh the page, it redirects me back to the logi ...

TypeScript's version of Java's enum (or C#'s structure)

I'm facing the challenge of creating an enum in Typescript that mimics the functionality of Java enums. In TypeScript, only integer-based enums like C# are supported, unlike in Java where we can have custom objects with non-integer related properties ...

Allowing the use of a string as a parameter in a Typescript constructor

Currently, I am utilizing TypeScript to create a constructor for a model within Angular. One of the attributes in the model is configured as an enum with specific string values. Everything functions well if an enum value is passed to the constructor. The i ...

Encountering problems while building Angular and Dot Net Core 2.0 Integration

I am encountering an issue where I am unable to build the Angular template using Dot Net Core/Standard 2.0 After downloading Dotnet core 2.0 and VS 2017 15.3, I followed the setup wizard to create a simple "hello world" project. Additionally, I installed ...

Unregistered outlet name unrecognized

I am currently working on developing a tabs component within one of my components, utilizing named outlets for this purpose. At the moment, I have my default outlet set up to display each page, and I would like to incorporate a named outlet within one of ...

What is the best way to access variables within a function from an external function in Typecript?

On my HTML page, I am invoking a method with parameters using the onchange event. Once I retrieve the value, I trigger function2 on the click of another button. I am looking to access the variable from function in function2 within the same class. My implem ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

How can I retrieve all values from an input number field that is created using *ngFor in Angular?

In my table, I have a list of cart products displayed with a quantity field. Users can increase or decrease the quantity using options provided. Currently, if I place an update button inside a loop, it creates separate buttons for each product. However, I ...

The observable of type 'any' does not contain the property 'subscribe'

When trying to extract data from googleTagmanger, I encountered an error stating that "Property 'subscribe' does not exist on type 'Observable'". Below is the code snippet I used: this.translate.get('newtest.testsimulation'). ...

Mistakes encountered when compiling TypeScript Definition Files

I am looking to convert my JavaScript files (*.js) to TypeScript files (*.ts) in my ASP.net MVC5 application (not an Asp.net Core app). I am using Visual Studio 2015. After downloading the TypeScript Definition Files into the Scripts\typings\ fol ...

Angular: the xhrRequest is failing to be sent

I am facing an issue with a service function that handles an HTTP post request. The request does not get sent for some reason. However, when I add a subscription to the post method, the request is successfully executed. In other services that have the sam ...

Guide to adding an optional parameter in the base href element within an Angular application

Hey there! I need to set an optional parameter so that either of the following URLs will work: http://myWebsiteName/myRouterPath or In this case, "mango" is the optional parameter. ...

Utilizing Material-UI with MobileDialog HOC in TypeScript: A Beginner's Guide

I'm running into an issue while trying to implement withMobileDialog in my TypeScript code. Below is the snippet of my code, inspired by a code example from the official documentation. import withMobileDialog, { InjectedProps } from "@material-ui/co ...

Invoke a method in a child component from its parent component

Is there a way to trigger a function on a child component from the parent component? In my scenario, I have a ModalComponent (parent) and a MessageComponent (child), and I need them to communicate. In Angular 1, this was achievable through a shared service ...

Updating icon of a row in a table based on its position with *ngFor

I am currently working with a table that contains a list of songs. My goal is to toggle the source of an icon in a specific row based on its index (for actions like play/pause, like/unlike). However, at the moment, the icon only changes in the first row re ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...

A guide on exposing TypeScript classes globally through a WebPack bundle in JavaScript

Currently delving into TypeScript, my aim is to gradually replace JS with TS. However, due to having numerous JS files, my strategy involves creating new classes in TS and incorporating them into my existing JS files for the time being. Eventually, I plan ...

Status:0 was received as the response from URL:null during the REST call made from my iOS Ionic application

I am currently facing an issue with a rest call in my Ionic app. The call works fine on Android devices but encounters problems on iOS devices. Below is the implementation of the rest call in my Ionic service. import { Http } from '@angular/http&apos ...

How can I get rid of the table borders and set colors for every other row in the

How can I remove the border lines from a table and assign colors to alternate rows in the table? Follow this link for the code: https://stackblitz.com/angular/kooxxyvddeqb?file=app%2Ftable-sticky-columns-example.css Thank you in advance ...

Angular 2: Store all form inputs within a JSON object upon submission

I am working on a form that has multiple fields and I need to retrieve the data once it is submitted. This is the code in component.html : <div class="ui raised segment"> <h2 class="ui header">Demo Form: Sku</h2> <form #f="ngFor ...