angular 4: call a method from a different component

Sivvio picture Sivvio · Jul 19, 2017 · Viewed 28.3k times · Source

I have 2 sibling components, I am doing an http request in one component, and if a particular condition happens, it should make another http request, written in another component. So I should be able to call the method within the first component.

this is the first component:

import { Component, OnInit, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { SendCardComponent } from '../send-card/send-card.component';

@Component({
  selector: 'app-input-field',
  templateUrl: './input-field.component.html',
  styleUrls: ['./input-field.component.css'],
})

export class InputFieldComponent implements OnInit {

value = '';
output = '';
@Inject(SendCardComponent) saro: SendCardComponent;

constructor(private http : Http) { }
onEnter(value: string) { 

this.value = value;


this.http.post('http://localhost:5000/APIconversation/', {"val":value})
  .map(response=>response.json())
  .subscribe(
      data => {

            this.output = data.result.fulfillment.speech,
            if(data.result.fulfillment.speech == 'test'){
                saro.sendCard('done', '1' );   
            }               

       });

 } 

I'm trying to call sendCard() defined in sendCardComponent, from InputFieldComponent which looks like this:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-send-card',
  templateUrl: './send-card.component.html',
  styleUrls: ['./send-card.component.css']
})

export class SendCardComponent implements OnInit {

constructor(private http : Http) { }

ngOnInit() {

}

 output = '';

 sendCard(value:string, id:number){
   this.http.post('http://localhost:5000/APIconversation/', {"val":value})
  .map(response=>response.json())
  .subscribe(
      data => {

             this.output = data.result.fulfillment.messages[1].payload.options[id].type = $('#'+(id+1)+'>span').html();  

      });
} //sendCard

}

I get an error when calling saro.sendCard:

[ts] cannot find name 'saro'

What am I doing wrong?

Answer

Rahul Singh picture Rahul Singh · Jul 19, 2017

Create a instance of SendCardComponent in the InputFieldComponent

import { Http } from '@angular/http';
import { SendCardComponent } from '../send-card/send-card.component';

export class InputFieldComponent{

    //your other variables and methods

    constructor(private http : Http) { }

    let saro = new SendCardComponent(this.http);

    saro.sendCard()

}