将API javascript添加到angular 2指令?

时间:2017-05-02 21:03:33

标签: javascript angular angular2-directives

我找不到任何关于此的好文档。

假设我有第三方库/ api,我想将它实现为angular 2指令。我该怎么办?

鉴于以下内容:

 <script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>

    <script>
      var linkHandler = Plaid.create({
       env: 'sandbox',
       clientName: 'Plaid Sandbox',
       // Replace '<PUBLIC_KEY>' with your own `public_key`
       key: '#####',
       product: ['auth'],
       onSuccess: function(public_token, metadata) {
         // Send the public_token to your app server here.
         // The metadata object contains info about the
         // institution the user selected and the
         // account_id, if selectAccount is enabled.
          console.log("Token: " + public_token + " Metadata: " + metadata);
       },
       onExit: function(err, metadata) {
         // The user exited the Link flow.
         if (err != null) {
        console.log("Error: " + err);
         }
         // metadata contains information about the
         // institution that the user selected and the
         // most recent API request IDs. Storing this
         // information can be helpful for support.
       }
      });
      // Trigger the standard institution select view
      document.getElementById('link-button').onclick = function() {
       linkHandler.open();
      };

1 个答案:

答案 0 :(得分:0)

在索引中导入外部API的脚本,或者在脚本部分中使用angular-cli。然后,创建一个这样的指令(代码未经过测试):

链接 - initialize.directive.ts

import {Directive} from '@angular/core';

declare const Plaid: any;

@Directive({
  selector: '[linkInitialize]'
})

export class LinkInitializeDirective {
  linkHandler: any;

  constructor() {
    this.linkHandler = Plaid.create({
       env: 'sandbox',
       clientName: 'Plaid Sandbox',
       // Replace '<PUBLIC_KEY>' with your own `public_key`
       key: '#####',
       product: ['auth'],
       onSuccess: function(public_token, metadata) {
         // Send the public_token to your app server here.
         // The metadata object contains info about the
         // institution the user selected and the
         // account_id, if selectAccount is enabled.
          console.log("Token: " + public_token + " Metadata: " + metadata);
       },
       onExit: function(err, metadata) {
         // The user exited the Link flow.
         if (err != null) {
            console.log("Error: " + err);
         }
         // metadata contains information about the
         // institution that the user selected and the
         // most recent API request IDs. Storing this
         // information can be helpful for support.
       }
      });

      // Trigger the standard institution select view
      document.getElementById('link-button').onclick = function() {
         linkHandler.open();
      };
    }
}

也许,this question指出了正确的方向。