1

How do I get the this.ID in the OnSuccess and in OnFailure?

I'm trying to import a dictionary into my angular project using pagemethods.

ID:number = 1;

ngAfterViewInit() {
     window['PageMethods'].getCustomAction(this.OnSuccess, this.OnFailure);
}

OnSuccess(succes:any) 
{
    if(1 == this.ID)
    {
         //Code
    }
}

OnFailure(error:any) 
{

}
Kapein
  • 165
  • 13

1 Answers1

3

Just wrap the callback methods in a lambda to preserve the this context:

window['PageMethods'].getCustomAction(
    (success: any) => this.OnSuccess(success), 
    (error: any) => this.OnFailure(error)
);

Then you can use your class members in OnSuccess and OnFailure.

rinukkusu
  • 20,045
  • 4
  • 57
  • 66
  • It works perfectly, thank you. I have no idea how I should have learned this, any advice how to learn these things? – Kapein Nov 09 '16 at 13:57
  • 1
    Well, the `this` context in JS is really a magic thing. So a rule of thumb is to always use lambdas (`() => ...`) instead of inline functions, because they automatically bind to the context in which they have been defined and just don't pass functions only, like you did in your question. Then you should be fine :D – rinukkusu Nov 09 '16 at 14:02
  • 1
    A gotcha with lambdas is though, that if you want to add more lines to be executed, you have to explicitly return something, if it's needed, while lambdas without the curly braces body implicitly return the value, they are called with. [More on this here.](http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6/23045200#23045200) – rinukkusu Nov 09 '16 at 14:05
  • Btw you don't need to add `any` in the lambda heading since it's implicitly of type `any` if not stated otherwise. – rinukkusu Nov 09 '16 at 14:10
  • removing the :any results in [ts] parameter 'error' implicitly has an 'any' type. – Kapein Nov 09 '16 at 14:14
  • 1
    Uh, it's a mere warning, iirc - but if that's the style guide for TypeScript, I'll add it. (following Angular 2 Dart for too long now, I guess) – rinukkusu Nov 09 '16 at 14:16