在组件内部的 nativescript angular2 中处理 'back' 按钮

Handling 'back' button in nativescript angular2 inside component

我正在尝试处理 'back' 按钮,如 中所示。提出了两种方法,都运行 ok。我的问题是如何与组件的本地数据交互,因为 'android.on' 是一个全局事件。

我想做的是在我的组件再次从另一个显示(用户通过点击 'back' 关闭)接收控制时刷新显示(只需更新 ngFor 中引用的列表的模型)按钮)。

我一直在尝试访问 'activityBackPressedEvent' 属性,但找不到访问组件数据的方法 ('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);
    }
}

问题是应用程序事件 activityBackPressedEvent 是本地事件而不是 Angular 事件。因此,在那种情况下,要保留 this 的含义,您需要良好的旧 this-that JavaScript 模式。

以下是修改代码使其按预期工作的方法:

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);
    });
}