[英]angular 4: call a method from a different component
我有2個兄弟組件,我在一個組件中做一個http請求,如果發生特定情況,它應該發出另一個http請求,寫在另一個組件中。 所以我應該能夠在第一個組件中調用該方法。
這是第一個組成部分:
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(),如下所示:
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時出錯:
[ts]找不到名字'saro'
我究竟做錯了什么?
在InputFieldComponent中創建SendCardComponent的實例
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()
}
您有2個問題需要解決。
首先,如果要使用依賴注入,則組件需要具有父子關系。 因此,在您的情況下,如果InputFieldComponent
是SendCardComponent
的子SendCardComponent
,則可以使用簡單(構造函數)依賴項注入從InputFieldComponent
獲取父SendCardComponent
的實例。
這就把我們帶到了第二個問題 - 實施。 如果我想做上述事情,那么我最終會:
export class InputFieldComponent implements OnInit {
value = '';
output = '';
constructor(private http : Http, private saro: SendCardComponent) { }
onEnter(value: string) {
this.value = value;
this.saro.methodOnSendCardComponent();
......
如果存在其他關系 - 其中InputFieldComponent
是SendCardComponent
的父SendCardComponent
,則可以使用SendCardComponent
從InputFieldComponent
獲取@ViewChild
的實例。
但是 ,如上所述,上述兩種方法都要求您更改視圖層次結構。 如果這兩個組件需要保持兄弟姐妹,那么上述兩個都不會起作用。
通過進一步考慮,如果您只需要訪問SendCardComponent
來使用它的邏輯(即方法),為什么不將該邏輯抽象到服務,然后您可以在層次結構中的任何位置使用該服務? 這非常巧妙地繞過了你現在的問題,並且總的來說是合理的建議。 老實說,您的組件應該將他們的行為集中在更高級別的問題上,並且盡可能地將其“外包”到服務上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.