gpt4 book ai didi

angular - navigateByUrl 无法路由应用程序

转载 作者:行者123 更新时间:2023-12-04 14:47:41 24 4
gpt4 key购买 nike

我在标签页上有一个按钮,可以通过删除存储条目为用户重置应用:

export class Tab1Page {

constructor(private router: Router, private storage: Storage, private toastController: ToastController) { }

async resetSettings() {
await this.storage.remove('welcomeComplete');

const toast = await this.toastController.create({
message: 'Your settings have been reset.',
duration: 2000
});
await toast.present();

console.log('before');
this.router.navigateByUrl('/');
console.log('after');
}
}

在浏览器调试器中,我可以看到该条目正在从存储中删除。我也收到了 toast 。

但是,由于某种原因,navigateByUrl 方法似乎没有被触发。上述页面位于 url '/tabs/tab1'。两个 console.log() 语句都执行了,控制台没有错误。

我是前端开发的新手,如果这是一个基本的新手问题,请道歉。


更新

我的 app-routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { WelcomeGuard } from './welcome/welcome.guard';

const routes: Routes = [
{
path: '',
loadChildren: './tabs/tabs.module#TabsPageModule',
canActivate: [WelcomeGuard]
},
{
path: 'welcome',
loadChildren: './welcome/welcome.module#WelcomePageModule',
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { enableTracing: true, preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule {}

我的welcome.guard.ts

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, CanActivate } from '@angular/router';
import { Observable } from 'rxjs';
import { Storage } from '@ionic/storage';

@Injectable({
providedIn: 'root'
})
export class WelcomeGuard implements CanActivate {

constructor(private router: Router, private storage: Storage) {}

async canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> {

const welcomeComplete = await this.storage.get('welcomeComplete');

if (!welcomeComplete) {
this.router.navigateByUrl('/welcome');
}
return true;
}
}

我已将我的 resetSettings() 更改为以下内容:

  async resetSettings() {
await this.storage.remove('welcomeComplete');

const toast = await this.toastController.create({
message: 'Your settings have been reset.',
duration: 2000
});

toast.onDidDismiss().then(() => {
this.router.navigateByUrl('');
});

await toast.present();
}

更改 resetSettings() 并没有解决问题。

最佳答案

这是你的后卫有问题,下面更改welcome.guard.ts可以帮助

 if (!welcomeComplete) {
this.router.navigateByUrl('/welcome');
return false;
}
return true;

原因:

在resetSetting函数中调用后

toast.onDidDismiss().then(() => {
this.router.navigateByUrl('');
});

它尝试导航到与路由数组中的第一个对象匹配的 url : ''

...
{
path: '',
loadChildren: './tabs/tabs.module#TabsPageModule',
canActivate: [WelcomeGuard]
}
....

然后它执行保护功能,然后您在任何情况下都返回 true,这意味着页面已获准导航到“/”,并且您在/tabs/tab1 中,这是当前的路线设置,所以它什么也不做,并且停留在同一页面上。

关于angular - navigateByUrl 无法路由应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55259848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com