Kevin192291
Kevin192291

Reputation: 2117

Angular 2 can't get value from function

I am using musale/angular2-stripe Everything is working, the problem is that I can't seem to get a value out of the component.

      openCheckout() {
    this.disabled = true;
    var handler = (<any>window).StripeCheckout.configure({
      key: 'pk_test_tS0hXmE0hfvaaPytUdgRIdwD',
      locale: 'auto',
      token: function (token: any) {
        debugger;
        this.token = token;
        //GET OUT FROM HERE< HTTP POST, EMMIT THE VALUE, ANYTHING!
        debugger;
      }
    });

    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: 2000
    });

    this.globalListener = this.renderer.listenGlobal('window', 'popstate', () => {
      handler.close();
    });
  }

Upvotes: 0

Views: 78

Answers (1)

Suraj Rao
Suraj Rao

Reputation: 29625

The issue seems to be because you are using a regular function which changes the this scope to the function object.

You can either set another variable to this before setting the callback and use it to save token.

 openCheckout() {
    this.disabled = true;
    let self=this;
    var handler = (<any>window).StripeCheckout.configure({
      key: 'pk_test_tS0hXmE0hfvaaPytUdgRIdwD',
      locale: 'auto',
      token: function (t: any) {
        debugger;
        self.token = t;
        //GET OUT FROM HERE< HTTP POST, EMMIT THE VALUE, ANYTHING!
        debugger;
      }
    });

Or my preferred alternative is to use Arrow Function which does not bind this and its value will still be of the class.

 openCheckout() {
    this.disabled = true;
    var handler = (<any>window).StripeCheckout.configure({
      key: 'pk_test_tS0hXmE0hfvaaPytUdgRIdwD',
      locale: 'auto',
      token: (t: any) => {
        debugger;
        this.token = t;
        //GET OUT FROM HERE< HTTP POST, EMMIT THE VALUE, ANYTHING!
        debugger;
      }
    });

Upvotes: 1

Related Questions