Reputation: 2074
I am writing an application using Angular 2 and a Google Api that uses a callback to return results.
I cannot seem to get the results returned to the component. Typescript has taken over 'this' and I am not sure how to get results from the callback functions context back to the Component's class context.
Here is the basic sample code:
@Component({
selector: '...',
viewProviders: [...],
templateUrl: '...',
directives: [...],
providers: [...]
})
export class TestComponent {
new google.visualization.Query('...')
.send(function handleResponse(response : any){
let datatable = response.getDataTable();
...
results.push(item);
}
this.viewCollection = results; //this no longer refers to the TestComponent
});
...
}
Upvotes: 0
Views: 731
Reputation: 6432
You have to use "fat arrow ()=>
" . It was added in EcmaScript6 and replaces the function keyword among other things. In a type position, =>
defines a function type where the arguments are to the left of the => and the return type is on the right.
The motivation for a fat arrow is:
You don't need to keep typing function (So, it will be anonymous)
It lexically captures the meaning of this
It lexically captures the meaning of arguments
Update your code with this code snippet
@Component({
selector: '...',
viewProviders: [...],
templateUrl: '...',
directives: [...],
providers: [...]
})
export class TestComponent {
new google.visualization.Query('...')
.send((response : any)=> {
let datatable = response.getDataTable();
...
results.push(item);
}
this.viewCollection = results; //this will refer to the TestComponent
});
...
}
Hope you will get your answer :)
Upvotes: 1
Reputation: 68
If you want to keep the context, use the fat arrow syntax () => {} instead of function expression.
Here is how I would rewrite your component with arrow syntax:
export class TestComponent {
send() {
new google
.visualization.Query('...')
.send((response: any) => {
let datatable = response.getDataTable();
response.forEach(item => {
results.push(item);
});
this.viewCollection = results;
});
}
Upvotes: 0