Reputation: 35
I'm trying to handle 'back' button as shown in Nativescript handling back button. There are two methods proposed, and both run ok. My problem is how to interact with my component's local data, since 'android.on' is a global event.
What I want to do is to refresh the display (just by updating the model of a list referenced in an ngFor) when my components receives control again from another display (which the users closes by tapping 'back' button).
I've been trying to access 'activityBackPressedEvent' properties, but I can't find a way to access component data ('shopList').
import { Component, OnInit, ViewChild } from "@angular/core";
import { Router } from "@angular/router";
import { RouterExtensions } from "nativescript-angular/router";
import { Page } from "ui/page";
import { ObservableArray } from "tns-core-modules/data/observable-array";
import { TokenModel } from "nativescript-ui-autocomplete";
import { RadAutoCompleteTextViewComponent } from "nativescript-ui-autocomplete/angular";
import { Utils } from '../../utils';
import * as SocialShare from "nativescript-social-share";
import { android, AndroidApplication, AndroidActivityBackPressedEventData } from "application";
import * as application from "tns-core-modules/application";
import {topmost} from "ui/frame";
@Component({
//selector: "Shopping",
moduleId: module.id,
templateUrl: "./shopping.component.html",
styleUrls: ['./shopping.component.css']
})
export class ShoppingComponent implements OnInit {
shopList: string[] = [];
constructor(private page: Page, private router: Router, private routerExt: RouterExtensions) {
this.shopList = [];
this.shopList.push ('sugar');
this.shopList.push ('milk');
}
reload(args: AndroidActivityBackPressedEventData): void {
console.log ('back pressed');
console.log (this.shopList); // <<--- "undefined"
}
ngOnInit(): void {
android.on(AndroidApplication.activityBackPressedEvent, this.reload);
}
}
Upvotes: 1
Views: 1331
Reputation: 9670
The thing is that the application event activityBackPressedEvent
is a native event and not an Angular one. So in that case to preserve the meaning of this
you need the good old this-that JavaScript pattern.
Here is how to modify your code to work as expected:
reload(args: AndroidActivityBackPressedEventData): void {
console.log ('back pressed');
console.log (this.shopList); // <<--- "[milk, sugar]"
}
ngOnInit(): void {
let that = this;
android.on(AndroidApplication.activityBackPressedEvent, (args: AndroidActivityBackPressedEventData) => {
that.reload(args);
});
}
Upvotes: 1