在angular 4项目中,当我从url中删除#时。删除#后我面临页面刷新相关问题

问题描述 投票:2回答:1

当我使用以下代码从angular 4项目中删除#时。在app.module.ts文件中

imports: [
...
RouterModule.forRoot(routes, { useHash: true })  // remove second argument
]

在提供者

@NgModule({
.....
providers: [
  // Below line is optional as default LocationStrategy is 
PathLocationStrategy
{provide: LocationStrategy, useClass: PathLocationStrategy} 
 ]
})

使用此代码,我可以从网址中删除#。但是当我刷新页面时,它会转到localhost:4200。以前(当我有刷新页面的#时)它不会进入默认页面localhost:4200.how来处理这个刷新错误而没有#in url in angular 4

angular angular4-router
1个回答
1
投票
Add this in App component 

When refresh it will load app component ngOninit

get token or Return url values using router

      const id = this.route.snapshot.params['token'];
        const returnUrl = this.route.snapshot.params['returnUrl'];
        if (id && returnUrl) {
            const appUser = new AppUser();
            appUser.id = id;
            appUser.user = new UserInfo();
            this._storage.setObj('token', appUser);
            const encodedReturnUrl = decodeURIComponent(returnUrl);
            this._authService.populate(encodedReturnUrl);
        } else {
            this._authService.populate();
        }

Auth服务是一个核心模块,它将在登录和刷新时自动化。

使用App组件中的令牌值获取当前用户详细信息。

 populate(returnUrl: string = '') {

      if (!returnUrl) {
              this.router.navigate([/login]);
                        } else {
       this.router.navigate([returnUrl]);
                        }
        }
© www.soinside.com 2019 - 2024. All rights reserved.