问题
I've got a Cordova app running on my Android device to show some news retrieved from a web service. As I'm using Typescript and Angular I've got a service holding my news like so:
class NewsService {
news: News[];
}
I'd like to save those news on Cordova's pause event, so I built a service to do that, injected it into my NewsService and added an event handler with a corresponding callback:
static $inject = ["$http", "newsApp.LocalStorageService"];
constructor(private $http: ng.IHttpService, private storageService: IStorageService) {
document.addEventListener('pause', saveNews, false);
}
saveNews(){
this.storageService.save(this.news);
}
My problem is that this.storageServcie
is undefined by the time the saveNews
-Method is called. Maybe the app is already terminated and being "garbage collected"? Can anybody confirm my suspicion or is there anything I'm doing wrong? How did you solve this problem in your app? I'd appreciate any help!
回答1:
When you define your event binding in
document.addEventListener('pause', this.saveNews, false);
your method is simply not declared yet. Take a look at this TypeScript example:
class Test {
greeting: string;
constructor(message: string) {
console.log(greet)
}
greet() {
return "Hello, " + this.greeting;
}
}
It transpiles to this JavaScript:
var Test = (function () {
function Test(message) {
console.log(greet);
}
Test.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Test;
})();
You would expect to get a function-reference, but hoisting wont work here, because every method is a reference for an anonymous function and the prototype-fields for these functions are simply not declared yet.
Encapsulate it in a lambda function will work:
document.addEventListener('pause', ()=>this.saveNews(), false);
来源:https://stackoverflow.com/questions/34921266/saving-the-application-state-on-cordovas-pause-with-angular