Tips for sending data returned asynchronously from an Observable in Angular from a Child component to its Parent

I am facing a challenge passing Async data from child to parent component. When I try to access console.log(this.values) within the ngAfterViewInit() method in the parent component's HTML page load, it returns an empty value. However, upon clicking the apply button in the child component, an event is emitted and the console.log(this.values); inside the getValues($event) method successfully prints the values.

Below is my parent component .ts file:

name = 'ViewUI';
@ViewChild('ChildValues', { static: false }) childReference: ChildComponent;

 ngAfterViewInit() {
  this.values = this.childReference.this.responseValues;
  console.log(this.values);
  mapResponse(this.values);
}

In this case, `mapResponse(this.values)` method runs before the data is retrieved from `this.values` in the child component.
getValues($event) {
  this.values = $event;
  console.log(this.values);
  this.apply();
}

This is my parent component .html file:

<app-child #ChildValues (getEvent)=" getValues($event)" [name]="name"></app-child>

Here is my child component .html file:

<button (click)="applyResponses()" mat-raised-button>
  Apply
</button>

And lastly, here is my Child component .ts file:

  export class ChildComponent implements OnInit {
      responseValues = {
            names: [], ages: []
        };
      @Output() getEvent = new EventEmitter < any > ();
      @Input() name: string;
    
      ngOnInit() {
        this.getNames();
        this.getAges();
        console.log(this.name);
      }
    
     getNames() {
       this.apiService.getnames(Id).subscribe((names) => {
         this.responseValues.names = [names[0].name];
        });
     }
    
     getAges() {
       this.apiService.getages(Id).subscribe((ages) => {
         this.responseValues.ages = [ages[0].age];
        });
     }
      applyResponses() {
        this.getEvent.emit(this.responseValues);
        console.log(this.responseValues);
      }
    }

Any ideas on how to retrieve data from the child to the parent component during the parent page load?

Answer №1

Instead of defining a new emitter in the ngOnInit of the child component, why not try creating one there?

@Output()dataReceived= new EventEmitter < any > ();

ngOnInit()
{
   forkJoin(this.getNames(),this.getAges()).subscribe(([names,ages]:[any[],any[]])=>{
       this.dataReceived.emit({names:names,ages:ages})
   })
}

How about handling the emitted data in your parent component like so:

<app-child (dataReceived)="storeData($event)"></app-child>
storeData(data:any)
{
    console.log(data.names,data.ages)
}

Note: This is a response to a question from a comment. It's important to acknowledge that the data may not always be received immediately. To simulate a delay in server response, import 'delay' from 'rxjs/operators'

import {delay} from 'rxjs/operators'

Update the subscription to include a delay of 10 seconds:

this.apiService.getages(Id).pipe(
  delay(10000))
  .subscribe((ages) => {
     this.responseValues.ages = [ages[0].age];
    });

If you click the button before 10 seconds, the data may not be available yet.

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

Make sure a Typescript array contains a particular value

Currently, I am in the process of developing a dropdown-style component where the value and options are separate props. My goal is to incorporate Typescript to ensure that the value remains a valid option. Although I could perform this validation at runtim ...

Tips on deactivating a div when a checkbox is selected

I am currently working with a checkbox element in my code: <md-checkbox checked.bind="addEventCommand.allDay" change.delegate="allday()">All Day</md-checkbox> When the above checkbox is true, I want to disable the following ...

An issue occurred at line 2, character 16 in the generateReport.service.ts file: TypeScript error TS2580 - The term 'require' is not recognized

I have a requirement in my app to generate a report in the form of a Word document with just a click of a button. Previously, I successfully accomplished this using the "officeGen" module in a separate project. You can find more information about the modul ...

Having difficulty implementing Angular 4 redirection for transitioning from old hash URLs to new non-hash URLs

In our single page application, we originally had a simple tab structure where each tab click led to a corresponding #url. Examples: , After transitioning to Angular 4, the urls no longer contain hash symbols. They now look like this: , I have added the ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

Is there a method to transform the event triggered by a child component via @Output into an observable stream within the parent component?

If we want to trigger a click event from a child component to the parent component, we can use @output in the child component and listen for that event in the parent component using the following syntax: <app-item-output (newItemEvent)="addItem($e ...

When merging multiple prop definitions using Object.assign in defineProps, Vue props can be made optional

I have defined a const called MODAL_OPTION_PROP to set common props for a modal: export const MODAL_OPTION_PROP = { modalOption: { type: Object as PropType<ModalOptionParams>, default: DEFAULT_MODAL_OPTION, }, }; I am trying to use it in ...

Issues with the ionViewDidLoad() function?

Having some trouble implementing Email Authentication in my project. The method ionViewDidLoad is not being recognized. I also tried using the method ionViewWillLoad() but that didn't work either. Any ideas on what might be causing this issue? Here&a ...

Guide to creating jest unit test for an observable variable exclusively utilized in a template resulting in the error "Property 'pipe' of undefined cannot be read"

Seeking help with creating unit tests for an Angular component that utilizes a constructor and observable variable in the HTML template. Below is the code snippet I am having issues with: voice-summary.component.ts export class VoiceSummaryComponent { v ...

Guide to accessing nested form controls within an array and object in Angular Reactive Forms

As a newcomer to Angular, I am in the process of creating a complex form for a food delivery application that I have been developing. The form I am currently working on is designed to allow me to add a new menu item to a restaurant's menu. In this A ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

It is not possible to bind an attribute to an element that already has a Bootstrap class applied to it

Currently, I am working on an Angular 2 web application and incorporating bootstrap for styling purposes. Within the app, there is a small triangle that needs to alternate between being visible and invisible. Here is the code snippet representing this elem ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...

Discovering the data type from its textual representation

Is it possible for TypeScript to automatically determine the generic argument of assertTypeof based on the value of expectedType? I am looking for a way to use the function below without having to specify number multiple times. playable example type Typ ...

I'm eager to showcase live, incoming data on the chart. However, I'm feeling a bit lost on how to proceed. Can you help

I am currently utilizing the line chart feature of ng2-charts in my Angular project. However, I am unsure how to create a graph with real-time data. Here is an example of some sample data being used for the line chart: lineChartData: ChartDataSets[] = [ { ...

My default value is being disregarded by the Angular FormGroup

I am facing an issue with my FormGroup in my form where it is not recognizing the standard values coming from my web api. It sets all the values to null unless I manually type something into the input field. This means that if I try to update a user, it en ...

Confirm that a specific value exists within an enumerated set

I am currently using Angular 13.3.9 and typescript 4.6.4. My main objective is to determine if a value is referencing an enum. Below is the code snippet: export enum HttpFunctionalErrorCodes { ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND', USER_ ...

Encountering this issue: Unable to access the property 'length' of an undefined variable

I'm currently developing an app using nuxt, vuetify 2, and typescript. Within the app, I have radio buttons (referred to as b1 and b2) and text fields (referred to as t1, t2, t3). When a user clicks on b1, it displays t1 and t3. On the other hand, w ...

Enhancing keyboard accessibility with the spacebar for radio buttons and check boxes in Angular 2

I am currently working on a form in Angular 2 that includes radio buttons and checkboxes. When tabbing through the fields, they are highlighted properly. However, I am facing an issue with the radio buttons - I want them to be selected when I hit the space ...

Typescript is missing Zod and tRPC types throughout all projects in the monorepo, leading to the use of 'any'

Recently, I've found myself stuck in a puzzling predicament. For the last couple of weeks, I've been trying to troubleshoot why the types are getting lost within my projects housed in a monorepo. Even though my backend exposes the necessary types ...