Sharing an object with a child component in Angular 2

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.

Answer №2

1- To start, within the service class, declare a variable called selectedUser of type user.

2- Next, in the parent component, use the method onUserRowSelect(user: User) to assign the selected user to this.yourService.selectedUSer, and then navigate to a specific route.

3- Lastly, in the child component, call

Console.log(this.yourService.selectedUSer);
to log the selected user.

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

What is the best way to activate ngModelChange for a custom input field?

I have developed a custom input component and here is the code: html: <input class='ctrl__counter-input' maxlength='10' type='text' [value]="counterValue" [ngModel]="counterValue" (ngModelChange)="onKey(in ...

Having trouble simulating a custom Axios Class in JavaScript/TypeScript

Here are the function snippets that I need to test using jest, but they require mocking axios. My attempt at doing this is shown below: // TODO - mock axios class instance for skipped Test suites describe("dateFilters()", () => { beforeEac ...

A discrepancy has arisen as the value within the array structure is being altered

I am facing an issue with the array structure of an object in my Angular front-end code. When I add values to the array based on selection, the object looks like this: todayRates: 10 yesterdayRates: 5 to: Array(1) 0: [3] length: 1 __proto__: Array(0) __pro ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

Using Typescript generics within a callback function

I am currently working on developing a versatile service that can fetch data from a remote source and create objects based on that data. @Injectable() export class tService<T> { private _data: BehaviorSubject<T[]> = new BehaviorSubject([]) ...

Angular and Webpack combined to output the build project to the specified output path

In the process of integrating my Angular client-side application with a server-side written in Spring, I am seeking a way to build the UI project and store it in the /target directory within the backend portion for easy installation using Maven. My uncer ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Is there a method or alternative solution for deconstructing TypeScript types/interfaces?

Imagine a scenario where a class has multiple type parameters: class BaseClass<T extends T1, U extends U1, V extends V1, /* etc. */ > Is there a method to consolidate these type arguments in a way that allows for "spreading" or "destructuring," sim ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Angular 10 issue: Cart quantity in header shared component does not update when changed from another component

Whenever I click on the 'Add to cart' button, I want the number of items in the cart icon on the header component to increase. Currently, this only works when I refresh the page. In order to achieve this, I am using a cart service to store globa ...

Dynamic Styling Based on Selected Menu Option in Angular 7

As I delve into learning Angular, I am exploring the creation of a dynamic navbar menu where the 'active' class is determined by the current page. While browsing, I came across this solution on Stack Overflow: Active Class Based On Selected Menu. ...

Injecting the environment into a service in an Angular project with multiple modules: A step-by-step guide

In my Angular project, I have developed two separate applications along with two libraries. In order to make use of a service across both apps, I created the service within one of the libraries. However, I am facing an issue because the service requires a ...

Potentially null object is present in a callback

The code I have is as follows: let ctx = ref.current.getContext("2d"); if(ctx){ ctx.lineWidth=1; // this line executes without errors ctx.strokeStyle=props.barStroke??"darkgray";// this line execut ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

The type '0 | Element | undefined' cannot be assigned to the type 'Element'

I encountered the following error: An error occurred when trying to render: Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>&apo ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

There was an error in Angular at core.js:6150 stating that the object is not iterable due to a

I am facing an issue in displaying the First Name of a user in an HTML file getFirstName(id: any){ this.users = this.afs.collection('users', ref => ref.where("uid", "==", id)).valueChanges(); this.users.subscribe(users => { ...

The 'cookies' property is not found on the 'Request' type

Currently, I am attempting to access a cookie within a NestJS controller. I have been referencing the documentation found at https://docs.nestjs.com/techniques/cookies#use-with-express-default Below is my implementation: import { Controller, Get, Render, ...

What is the best approach for handling server-side validation errors in Angular when making an HTTP call?

After following different tutorials, I have created a service that can transmit login details to the backend for validation and processing. Although I am able to generate appropriate error codes based on user input, I find myself wondering what to do next. ...

What is the proper way to integrate helmet.js with typescript?

Utilizing helmet from pure JavaScript according to the documentation is quite straightforward: const express = require('express') const helmet = require('helmet') const app = express() app.use(helmet()) However, I'm unsure how ...