【发布时间】:2021-11-08 17:43:49
【问题描述】:
我正在尝试在app.component 上使用IonRouterOutlet,这是代码
import { Component, ViewChild } from "@angular/core";
import { AlertController, IonRouterOutlet, Platform } from "@ionic/angular";
import { SplashScreen } from "@ionic-native/splash-screen/ngx";
import { StatusBar } from "@ionic-native/status-bar/ngx";
import { FcmService } from "@core/services/fcm-service/fcm.service";
import { AuthenticationService } from "@core/services/authenticatiion-service/authentication.service";
import { Location } from "@angular/common";
import { Plugins } from "@capacitor/core";
const { App } = Plugins;
@Component({
selector: "app-root",
templateUrl: "app.component.html",
styleUrls: ["app.component.scss"],
})
export class AppComponent {
@ViewChild(IonRouterOutlet, { static: true }) routerOutlet: IonRouterOutlet;
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private fcmService: FcmService,
private authService: AuthenticationService,
private alertController: AlertController,
private location: Location
) {
this.authService.checkToken();
this.initializeApp();
this.backButtonEvent();
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.authService.changeRoutes();
this.fcmService.initPush();
});
}
backButtonEvent() {
console.log('back button event');
this.platform.backButton.subscribeWithPriority(10, () => {
if (!this.routerOutlet.canGoBack()) {
console.log('cannot');
}
});
}
async presentAlertConfirm() {
const alert = await this.alertController.create({
cssClass: "my-custom-class",
header: "Confirm",
message: "Are you sure you want to exit ?",
backdropDismiss: false,
buttons: [
{
text: "Cancel",
role: "cancel",
cssClass: "secondary",
},
{
text: "Logout",
handler: () => {
this.authService.logout();
App.exitApp();
},
},
],
});
await alert.present();
}
}
但每次按下后退按钮时都会触发事件,但 routerOutlet 在尝试访问 canGoBack() 时会抛出未定义的错误。
TypeError: Cannot read property 'canGoBack' of undefined
有什么帮助吗?
【问题讨论】:
-
尝试将
@ViewChild(IonRouterOutlet, { static: true })更改为@ViewChild(IonRouterOutlet, { static: false }) -
staticto true 意思是:在变更检测运行前解析查询结果,尝试将true改为false查看。 -
将
static更改为 false 没有帮助。 -
我什至尝试删除静态仍然是
undefined