Davut Gürbüz Davut Gürbüz - 4 days ago 5
TypeScript Question

Reaching this when http install is done for Angular2

I've tried to simplify question and minimized the code below. What is trying to achieve is calling a callback function when http installation is done. Callback method is being called but

this
variable and its bound variables are not reachable because
this
be undefined when asyn load is done.

load(callBackFn)this.http.get(this.sourceAddress).subscribe(
op =>{
if(callbackFn)
{
callBackFn();
}
}

this.load(function()
{
//**THIS IS NULL HERE ? BUT ACTUALLY this.uniqueId is set**
$('#' + this.uniqueId).css("display", "block");
})

Answer

Not sure why you would want to do that way, seems a bit messy with callback functions when you could just access what ever class member you needed after you subscribe, but I guess that you would have to bind the this you wanted to the callback:

export class SomeComponent
{
    private sourceAddress = 'some/url';
    private uniqueId = 'spam';

    constructor(private http: Http)
    {
    }

    ngOnInit()
    {
        this.load(this.loadSuccess).bind(this);
    }

    load(callBackFn)
    {
        this.http
            .get(this.sourceAddress)
            .subscribe(
                response =>
                {
                    if (callBackFn)
                    {
                        callBackFn();
                    }
                },
                error =>
                {
                    console.log(error)
                });
    }

    loadSuccess()
    {
        $('#' + this.uniqueId).css("display", "block");
    }

}
Comments