Angular 角度:子组件在将数据传递给父组件后侦听返回
我是个新手,一直在努力寻找我需要的东西,但却找不到。请帮忙 假设这是具有所需参数的工作函数:Angular 角度:子组件在将数据传递给父组件后侦听返回,angular,Angular,我是个新手,一直在努力寻找我需要的东西,但却找不到。请帮忙 假设这是具有所需参数的工作函数: export class ChildComponent implements OnInit { ... datatable(params, callback) { this.service.getList(params).subscribe(response => { callback({ recordsTotal: response.records
export class ChildComponent implements OnInit {
...
datatable(params, callback) {
this.service.getList(params).subscribe(response => {
callback({
recordsTotal: response.recordsTotal,
recordsFiltered: response.recordsFiltered,
data: response.data
});
});
}
...
}
以上各项工作正常。但是我想让这个ChildComponent成为共享组件,所以我必须分离这个函数并将它放在ParentComponent下。请注意,下面的代码不正确,但我试图这样解释我的观点:
子组件:
export class ChildComponent implements OnInit {
@Output() source: EventEmitter<any> = new EventEmitter<any>();
datatable(params, callback) {
this.source.emit(params, callback).subscribe(response => {
callback({
recordsTotal: response.recordsTotal,
recordsFiltered: response.recordsFiltered,
data: response.data
});
});
}
...
}
@Component({
selector: 'parent-component',
template: '
<child-component (source)="getList($event)"></child-component>
'
})
export class ParentComponent implements OnInit {
constructor(private service: Service) { }
getList(params) {
return this.service.getList(params);
}
}
我知道我做错了。我需要ChildComponent通过ParentComponent的函数传递参数,然后侦听从那里返回的值。我如何以正确的方式做到这一点?谢谢。我认为您没有使用您定义的EventEmitter,但没有使用 也许吧 ParentComponent.ts
@Component({
selector: 'parent-component',
template: '
<child-component (source)="getList($event)"></child-component>
'
})
export class ParentComponent implements OnInit {
constructor(private service: Service) { }
getList(params) {
return this.service.getList(params).subscribe();
}
}
@组件({
选择器:“父组件”,
模板:'
'
})
导出类ParentComponent实现OnInit{
构造函数(私有服务:服务){}
getList(参数){
返回此.service.getList(params.subscribe();
}
}
我不认为这是正确的,因为我已经尝试过了。EventEmitter实际上似乎不支持在发出后订阅部分,但有其他方法可以正确执行吗?@14thsky是的,我的示例中有一个错误,现在它已修复,如果您可以发送一个示例,请greatthanks回复。这是示例代码-请查看我在代码中所述的注释。试试看,您提供的代码不包括任何订阅,我需要它在从父组件调用函数后订阅服务。
datatable(params, callback) {
this.service.getList(params).subscribe(response => {
callback({
recordsTotal: response.recordsTotal,
recordsFiltered: response.recordsFiltered,
data: response.data
});
this.source.emit('what ever you want to pass');
});
}
@Component({
selector: 'parent-component',
template: '
<child-component (source)="getList($event)"></child-component>
'
})
export class ParentComponent implements OnInit {
constructor(private service: Service) { }
getList(params) {
return this.service.getList(params).subscribe();
}
}