【问题标题】:I cant navigate to the index page, when i click back button in Angular当我单击 Angular 中的后退按钮时,我无法导航到索引页面
【发布时间】:2022-02-24 16:18:24
【问题描述】:

我有 Angular 项目。在索引页面上,我有按钮,这使我进入另一个页面。当我想返回索引页面时,我单击浏览器的返回按钮,然后只出现一个白色页面,而不是我的索引页面。你有同样的问题吗?

【问题讨论】:

标签: angular typescript


【解决方案1】:

据我所知,这不是角度路由的问题。我建议检查路由配置是否正确。

假设您在项目中设置了角度路由(this),您必须确保索引页面的路由已正确注册。在您的app-routing.module.ts 中应该有这样的内容:

const routes: Routes = [
  { path: 'another-page', component: AnotherPageComponent },
  { path: '', component: IndexPageComponent },
  { path: '**', redirectTo: '' }
]

在您的app.module.ts 中,确保BrowserModuleAppRoutingModule 已被导入。

如果角度路由配置正确,您也许可以启用路由调试来发现问题。其他答案表明这可能会有所帮助(herehere)。

【讨论】:

  • 首先,感谢您的时间。我有这个代码const routes: Routes = [ { path: 'categories', component: CategoriesComponent }, { path: 'hotels', component: HotelsComponent }, // i tried to add this, but it doesnot work { path: '/', redirectTo: '/' },];
  • @Irakli 啊,我们走了。您的代码中存在问题:将path: '/' 替换为path: ''(类似于我的示例),我相信它会起作用。
  • 谢谢,但我已经用另一种方法解决了这个问题
  • 没问题。我建议编辑您的问题,让其他人知道您的解决方案是什么,并将问题标记为已解决。
【解决方案2】:

我通过以下方式解决了这个问题: 我给了我的索引页(app.component.html)类“mainPage”

<div class="mainPage" #mainPage>
... // index page
</div>

然后我在 app.component.ts 中写了如下代码:

export class AppComponent implements OnInit{
  @ViewChild('mainPage') buttons!: ElementRef;
  constructor(private renderer: Renderer2, private el: ElementRef, private router: Router){
      
    router.events.subscribe((eve : any )=>{
        this.currentRoute = router.url;
        if(this.currentRoute == '/'){
          this.showIndex();
        } 
      });
  }
  
  currentRoute : string = "";\
ngOnInit(): void {

  }
  hideIndex(){
    this.renderer.addClass(this.buttons.nativeElement, "d-none");
  }
  showIndex(){
    this.renderer.removeClass(this.buttons.nativeElement, "d-none");
  }
  title = '';
}
    

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多