简体   繁体   中英

Unable to pass response object from one component to another in angular 2

import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FetchService } from '../fetch. Service';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  constructor(private FetchService : FetchService,private router : Router) { }
  ngOnInit(): void {
    this.getData()
  }
  @Input() items: any;
  getData(){
    this.FetchService.fetchData().subscribe(data => {
    this.items=data;
    console.log(this.items + "first")
    },
     error => console.error(error)
    )
    
    }
  
    second(){
      this.router.navigateByUrl("/second")
    }
}

In 2nd component HTML and Ts -

<app-first [items]="fetchBirds"></app-first>

export class SecondComponent implements OnInit {
  constructor() { }
  fetchBirds:any
  ngOnInit(): void {
    this.data()
  }

  data(){
    console.log(this.fetchBirds + "2nd")
  }
}

I have two component 1st and 2nd. I have response which I am able to fetch in 1st component.ts and printed in console. I am using @Input and passing it to 2nd component but its coming as undefined in 2nd component. Please help.

@Input is used to pass data from Parent component to Child component. Here your Second component appears to be parent.

When you use your First(child) component inside Second(parent) component like this -

<app-first [items]="fetchBirds"></app-first>

fetchBirds should belong to Parent (Second component) and it's value be fetched in second component.

And items should belong to Child (First component) and it's value will be fetched by using @Input like this -

 @Input() items: any;

In your case, you are fetching data from service in Child component and assigning it to items which is coming from Parent component.

Either fetch the value is Parent & pass it to child or if you can fetch in Child, you don't need @Input.

According to your code. Your are loading 1st component in 2nd component. So the parent component is 2nd component. Child component is 1st component. Also you need to pass data from 1st component to 2nd component which means there is a child to parent data passing. There for you need to use output() decorator.

2nd component (Parent component)

<app-first (dataEvent)="receiveData($event)"></app-first>

export class SecondComponent implements OnInit {

  constructor() { }

  data:any; //any or your model

  receiveData($event) {
    this.data= $event
  }
}

1st component (Child component)

export class FirstComponent implements OnInit {

  constructor(private FetchService : FetchService,private router : Router) { }

  ngOnInit(): void {
    this.getData()
  }

  @Output() dataEvent = new EventEmitter<string>();

  getData(){
    this.FetchService.fetchData().subscribe(data => {
    this.items = data;
    console.log(this.items + "first")
    this.dataEvent.emit(this.items);
    },
     error => console.error(error)
    )
    
    }

I agree with Priyesha, you don't need @Input in this case.

Just use @Inject and get the second component directly in first component. Any public properties or methods will be available:

import { Component, Inject, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
  
  protected items: any;

  constructor(
    private router: Router,
    @Inject(SecondComponent) protected component: SecondComponent) { }

  public ngOnInit(): void {
    this.items = this.component.fetchBirds;
    console.log('first:', this.items);
  }
  
  public second(): void {
    this.router.navigateByUrl("/second")
  }
}

Note this is only possible because <app-first></app-first> is contained in the html for SecondComponent, so SecondComponent can be accessed via DI in FirstComponent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM