angular 4:从不同的组件调用方法 [英] angular 4: call a method from a different component

查看:52
本文介绍了angular 4:从不同的组件调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个兄弟组件,我在一个组件中执行 http 请求,如果发生特定情况,它应该发出另一个 http 请求,用另一个组件编写.所以我应该能够在第一个组件中调用该方法.

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.

这是第一个组件:

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' );   
            }               

       });

 } 

我正在尝试从如下所示的 InputFieldComponent 调用 sendCardComponent 中定义的 sendCard():

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

}

调用 saro.sendCard 时出错:

I get an error when calling saro.sendCard:

[ts] 找不到名字 'saro'

[ts] cannot find name 'saro'

我做错了什么?

推荐答案

在 InputFieldComponent 中创建 SendCardComponent 的实例

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()

}

这篇关于angular 4:从不同的组件调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆