繁体   English   中英

如何将回调函数(带有 http 请求)从父组件传递到 Angular 中的子组件

[英]How pass a callback funcion (with a http request) from a parent component to child component in Angular

我想将具有 http 请求的 function 从父组件传递给子组件,然后从子组件执行请求。

我的代码如下:

// myService
constructor(private http: HttpClient)
getIds(id) {
    // return of(['a', 'b', 'c', id]); with this works
    return this.http.get(apiUrl)  // with this doesnt work
 }

// parentComponent.ts
callbackFunction = this.myService.getIds;
constructor(private myService: MyService) { }

// parentComponent.html
<child-component [callbackRequest]="callbackFunction"></child-component>

// childComponent.ts
@Input() callbackRequest;
ngOnInit() {
   this.callbackRequest('d');
}

最让我困惑的是,如果我从服务返回一个可观察的构建,如果它有效。 调试时,我看到如果对服务的调用到达。 我得到的错误如下: ERROR TypeError: Cannot read property 'get' of undefined

你能行的:

 // myService constructor(private http: HttpClient) getIds(id) { // return of(['a', 'b', 'c', id]); with this works return this.http.get(apiUrl) // with this doesnt work } // parentComponent.ts callbackFunction = this.myService.getIds.bind(this.myService); constructor(private myService: MyService) { } // parentComponent.html <child-component [callbackRequest]="callbackFunction"></child-component> // childComponent.ts @Input() callbackRequest; ngOnInit() { this.callbackRequest('d'); }

.bind(this) 是解决方案,因为 function 将能够使用父实例(您可以看到,当您不绑定它时,一切都变为未定义)

当使用 Angular 中的@Input绑定传递它的引用时, getIds function 中this关键字的含义就会丢失。 它在您返回of([...])时起作用,因为没有使用this 有关回调中this关键字含义的规范帖子,请参见此处

有两种解决方案

  1. 使用bind - 请参阅@GabrielSereno 的帖子
  2. 使用箭头函数

服务

public getIds = (id) => {
  return this.http.get(apiUrl);
}

零件

callbackFunction: any;;
constructor(private myService: MyService) { }

ngOnInit() {
  this.callbackFunction = this.myService.getIds;
}

模板

<ng-container *ngIf="callbackFunction">
  <child-component [callbackRequest]="callbackFunction"></child-component>
</ng-container>

使用回调 function 是否有特定原因?

通常我会尝试使一个组件“聪明”和一个“愚蠢”。
在您的情况下,父母决定做什么(HTTP 请求),孩子决定何时做。 而也许孩子也应该表现出结果。
因此,我决定在类似的情况下,我的孩子将在何时运行请求时通知父母,然后父母运行请求并将结果提供给孩子。

是的,这样我的孩子不仅需要一个 INPUT,还需要一个 INPUT 和一个 OUTPUT。 另一方面,我的孩子有一个明确定义的 INPUT 接口。 如果我只是提供一个回调方法,回调可能会返回任何东西。

我的孩子也几乎没有“逻辑”。 所有的魔法都在父母身上。 这使得为子组件编写单元测试变得非常容易。 而且对于父母来说,只有一个被嘲笑的孩子也很容易。

是的,JavaScript(因此也包括 TypeScript)允许.bind()之类的东西。 但根据我的经验,它似乎可以很快解决问题,但真正的努力是在后面。 它更难理解,也更难调试。 因此我通常会避免它。

只是解决问题的另一种方法。 选择您喜欢的零件并忽略 rest:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM