我有一个组件,它由触发功能的按钮和根据我从服务和该功能获得的数据生成元素的表组成 .
但我不得不拆分该组件,现在我只有一个组件上的按钮,以及其他组件上的数据的函数和表 .
在带按钮的第一个组件中,我将EventEmmiter设置为:
import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { ConceptService } from "app/services/rest/concept.service";
@Component( {
selector: 'co-calculation',
templateUrl: './co-calculation.component.html',
styles: []
} )
export class CoCalculationComponent implements OnInit {
dataSent: EventEmitter<any> = new EventEmitter();
constructor( private conceptService: ConceptService ) { }
ngOnInit() {}
calculate(){
this.conceptService.calculateCoDatabase().subscribe( (response:any) => {
this.dataSent.emit(response);
}); } }
在其他组件上,我有一个功能,当我点击按钮时我想要消除,而是想在功能启动时设置emit来替换服务订阅 .
第二部分:
从'@ angular / core'导入{Component,OnInit,Output,EventEmitter,Input};
import { ConceptService } from "app/services/rest/concept.service";
import { CoCalculationComponent } from "app/components/02_top/scm/co-calculation/co-calculation.component";
@Component( {
selector: 'co-database-table',
templateUrl: './co-database-table.component.html',
styles: []
} )
export class CoDatabaseTableComponent implements OnInit {
data;
constructor( private conceptService: ConceptService ) { }
ngOnInit() {
}
generateTable(){
this.conceptService.calculateCoDatabase().subscribe( (response:any) => {
this.data = response;
console.log('data');
//rest of function is irrelevant//
}
我不知道如何在第二个组件中触发函数并从第一个组件而不是服务订阅传递emit . 谢谢
2 回答
现在,这将取决于现在两个组件之间的关系 . 我们可以使用事件 Launcher ,如果我们有父子关系,并且你想在子项中单击按钮时调用父项的方法,向我们展示关系,我们可以解释如何执行它 .
如果它们根本不相关,那么你可以使用服务并在那里创建一个主题,它既可以是观察者,也可以是观察者 .
有这样的服务:
现在,在两个组件中注入服务,在第一个组件中单击按钮时调用如下函数:
在另一个组件中,在
ngOnInit()
中有这样的东西假设您有一个包含
<cost-calculation></cost-calculation>
和<cost-database-table></cost-database-table>
组件的父组件 .第1步:更改代码以将数据作为@Input这样获取
通知
data
现在@Input() data:any
Step2:删除generateTable()方法,数据将在onChange lifeCycle上更新
第3步:在您的父组件上将数据声明为变量,并创建将数据作为参数的create方法
//为简单起见删除了代码
Step4:Ony您的父模板添加以下内容
cost-calculation 组件将从服务获取数据并将其发出 . 当发出数据时,将调用父组件中的 updateData 方法,并将数据属性设置为发出的数据 .
然后,父项将发送的数据作为输入传递给 database-table 组件