【发布时间】:2021-09-13 05:23:47
【问题描述】:
我在连接到第三方 API PayPal BrainTree 的 Angular 组件时遇到问题,该 API 会动态地将 iframe 添加到组件主体。我需要保持连接和底层 html 持久,而不是与 api 断开连接。
有问题的组件与多个支付选项有关,其中一个选项连接到第三方 api。当另一个请求被触发以刷新支付方式时,就会出现问题,当这种情况发生时,支付选项会重新呈现,这会断开 API 并从组件中删除 iframe,然后再建立新的连接并创建新的 iframe。
Here is a working Minimum viable example for reference.
渲染的基础是
- 已发出 API 请求以获取付款选项
- 支付选项在循环中呈现
- 支付选项被渲染,LazyPaymentOptionComponent 和普通 PaymentOptionComponent 的组件不同
- 如果再次检查支付选项,整个组件将重新呈现,断开 API。
<div *ngFor="let option in payments$ | async">
<app-lazy-payment-option *ngIf="option.lazy"></app-lazy-payment-option>
<app-payment-option *ngIf="!option.lazy"></app-payment-option>
</div>
在 LazyPaymentOption 中,与第三方支付 API 的连接是在 ngAfterViewInit 期间建立的
@Component(...)
class LazyPaymentOptionComponent implements AfterViewInit {
ngAfterViewInit(): void {
this.thirdPartyService.connect().subscribe();
}
}
理想情况下,我需要防止 LazyPaymentOption 破坏和重新渲染,在 React 中我会使用 shouldComponentUpdate 但我在 Angular 的组件级别没有找到类似的东西。
我找到了 ChangeDetectorRef,但我似乎无法阻止组件破坏和重新渲染,例如。我希望我可以使用this.cd.detatch() 来防止卸载和重新渲染组件。
@Component(...)
class LazyPaymentOptionComponent implements AfterViewInit {
constructor(
private cd: ChangeDetectorRef,
private thirdPartyService: ThirdPartyService
) {}
ngAfterViewInit(): void {
this.thirdPartyService.connect().subscribe(() => {
// attempt to detach from change detection so the component doesn't re-render
this.cd.detatch();
});
}
}
在我手动实现之前,我能做些什么来阻止渲染循环吗?或者我应该尝试的其他任何事情,我已经深入研究了这个问题 2 天,但不确定我可以在哪里查看。
【问题讨论】:
标签: angular typescript braintree