简体   繁体   中英

How can I pass an Angular2 method in my component as the callback method of a third party library?

I've got an Angular2 application that references a third party library. I reference that library in one of my components via:

declare var thirdPartyLib: any;

Next I bind a button's click to the method below.

buttonClick() {
        thirdPartyLib.open({
            url: '{url goes here}',
            messageListener: function(eventData) {
                this.processResponse(eventData);
            }
        });
    }

    processResponse(eventData: any) {...}

The problem is that when it fires the messageListener function I get an error that it "can't read property processResponse of undefined." I understand that there is an issue of scoping to 'this', but how do I call that method on my component from within that function? Or is there another way completely to do something like this?

Just for completeness, I've also attempted the following:

buttonClick() {
        var myMethod = this.processResponse;
        thirdPartyLib.open({
            url: '{url goes here}',
            messageListener: myMethod
        });
    }

    processResponse(eventData: any) {...}

The problem with this method is that processResponse calls a service as this.someService.whatever(eventData.something); . Using this approach throws the same error but now for this.someService .

Thanks in advance for the help!

I think, you have two options.

1. Arrow functions

They will preserve the reference to current object in this .

buttonClick() {
    thirdPartyLib.open({
        url: '{url goes here}',
        messageListener: (eventData) => {
            this.processResponse(eventData);
        }
    });
}

processResponse(eventData: any) {...}

Or even shorter form: messageListener: eventData => this.processResponse(eventData)

2. "that" pattern

that (or differently named) variable may hold reference to current object.

buttonClick() {
    const that = this;
    thirdPartyLib.open({
        url: '{url goes here}',
        messageListener: function(eventData) {
            that.processResponse(eventData);
        }
    });
}

processResponse(eventData: any) {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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