处理组件内部的nativescript angular2中的“后退”按钮

时间:2018-08-14 07:48:40

标签: nativescript angular2-nativescript nativescript-angular

我正在尝试处理Nativescript handling back button中所示的“后退”按钮。提出了两种方法,两种方法都可以。我的问题是如何与组件的本地数据进行交互,因为“ android.on”是一个全局事件。

当组件再次从另一个显示器(用户通过单击“后退”按钮将其关闭)接收控件时,我想做的就是刷新显示器(仅通过更新ngFor中引用的列表的模型)。 / p>

我一直在尝试访问'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);
    }
}

1 个答案:

答案 0 :(得分:0)

问题是应用程序事件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);
    });
}