【问题标题】:How execute javascript after a component change in angular?组件更改角度后如何执行javascript?
【发布时间】:2021-05-05 05:42:28
【问题描述】:

当我在浏览器 localhost:4200/pay;id=1 中编写代码时,我的代码运行良好。这个显示带有由外部 javascript 生成的信用卡字段的支付组件(这个 javascript 脚本是从这个组件加载的)。但是,如果我来自另一个组件,支付组件不会显示信用卡字段,而是加载外部脚本。我该如何解决这个问题?

我的代码

first.component.ts

let datos = {
  id:'6'
}
this.router.navigate(['pay',datos]);

pay.component.ts

ngOnInit(): void {
    this.loadScripts();
}

 loadScripts() {
     this.dynamicScriptLoader.load('2payjs').then(data => {
       // Script Loaded Successfully
       console.log('All elements loaded successfully')
       this.loadElement();
 
     }).catch(error => console.log(error));
}

loadElement(){
    let that = this;
    let id = this.router.snapshot.paramMap.get('id');
    window.addEventListener('load', function() {
      // Initialize the JS Payments SDK client.
      let jsPaymentClient = new  TwoPayClient('AVLRNG');
  
      // Create the component that will hold the card fields.
      let component = jsPaymentClient.components.create('card');
  
      component.mount('#card-element');

      // Handle form submission.
      document.getElementById('payment-form').addEventListener('submit', (event) => {
        event.preventDefault();
    
        /// Extract the Name field value
        const billingDetails = {
          name: document.querySelector('#name').value
        };

        // Call the generate method using the component as the first parameter
        // and the billing details as the second one
        jsPaymentClient.tokens.generate(component, billingDetails).then((response) => {
          //console.log(response.token);
          let data = {
            token:response.token
          }
        }).catch((error) => {
          console.error(error);
        });
      });
    });
  }

【问题讨论】:

    标签: javascript angular


    【解决方案1】:
    const navigationExtras: NavigationExtras = {
       queryParams: {
           id: 1,
        },
        queryParamsHandling: 'merge'
    };
    this.router.navigate(['pay'], navigationExtras);
    

    您需要navigationExtras 才能在您的路由器链接中创建参数并能够被另一个组件获取

    【讨论】:

    • 我可以正确传递数据,在支付组件中我的外部库正确加载,但它不会生成卡片字段。如果我通过 url 直接打开支付组件,它会生成卡片字段
    【解决方案2】:

    已经解决了。我只是删除了窗口加载事件监听器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 2014-04-03
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多