External library promise fails in Ionic 2


#1

Dear Experts,

I am new to Ionic 2, and facing trouble while trying access the parent/calling context in the success promise function. I am trying to use the OData libraries provided in this link([http://datajs.codeplex.com/]).

OData.read accepts a URL object, and success and error callback. I already tried the below, however, this inside the callback comes as “not defined”.

A) Normal Javascript style:
this.items=[];
OData.read(request, SuccessCallback, ErrorCallback);

function SuccessCallback(data, response){
alert(JSON.stringify(data.results));
this.items = data.results;
//result is fetching the data but this is undefined. We need to set the data to a items variable,
//that is mapped to the view. But this is not defined.
}

function ErrorCallback(e){
//Here also this is not defined.
}

B) Arrow functions similar to Typescript function calls

OData.read(request,
(data, response) => {
alert(JSON.stringify(data.results));
this.items = data.results; // this is not defined
},
(error) => {
});

C) Then I tried setting it as a promise.

ionViewDidLoad(){
this.getData().then(
(data) => {
this.items= data; // this is still not defined
},
(error) => {
alert(JSON.stringify(error));
});
}

getData = () => {
return new Promise((resolve, reject) => {
OData.read(request,
(data, response) => {
alert(JSON.stringify(data.results));
resolve(data.results);
},
(error) => {
reject(error);
});
})
}

In all cases, this is coming as undefined. Could anyone please guide me as to what I am doing wrong. The same holds true for certain custom cordova plugins that we are using. Inside the callback of the cordova plugin, this is showing as undefined.

I have added the datajs script file in index.html and declared a Global variable OData, before @Component. Also added the plugin, and the plugin is working fine, however not able to set the response to member variables.

Cheers,
Vigil


#2

@iignatov - I have read your other blogs for fixing external library issues, though this seems to be different one. Tagging you to help find a resolution.

Thank You!