Angular 7 无路由组件重定向

Angular 7 component redirection without routing

使用我当前的 Angular 7 和 Firebase 设置,我遇到以下情况:

我有主要的应用程序组件,如果用户已登录,它会显示会员区域,否则会显示 public 区域。一切正常,但在注销或登录后显示正确的组件之前会有 1-2 秒的延迟。顺便说一句,我不想​​使用路由。因为我想用相同的 URL.

显示所有内容

您知道如何减少延迟吗?无论如何,这是进行身份验证的好习惯吗? 感谢您的帮助!

app.component.html

<div *ngIf="authService.isAuthorized(); else showLogin">
  <app-member></app-member>
</div>
<ng-template #showLogin>
  <app-public></app-public>
</ng-template>
<router-outlet></router-outlet>

然后是会员区和public区的组件:

member.component.html:

<button nz-button [nzSize]="size" nzType="primary (click)="authService.logout()">Logout</button>

public.component.html:

<button nz-button [nzSize]="size" nzType="primary" (click)="authService.login()">Login</button>

不知道没有路由怎么办。你为什么不想使用它? 就这么简单: 在你的 app-routing.module.ts 文件上使用 Angular 的 canActivate class。

为此,您需要实施验证服务来检查用户是否已登录。

示例:

   const routes: Routes = [
      {
        path: '',
        component: MemberComponent,
        canActivate: [YourAuthGuard],
      },
      {
        path: 'public',
        component: PublicComponent
      }
    ];
    @NgModule({
      imports: [...],
      exports: [...],
      providers: [ YourAuthGuard ]
    })
    export class AppRoutingModule { }

然后您可以使用 Angular class 路由器的 navigate () 方法从一个组件重定向到另一个组件。

希望对您有所帮助。

对于您的初始方法,我建议您使用一个变量作为可观察变量来定义用户是否被授权,而不是调用函数 authService.isAuthorized()。 您可以在您的 authservice 中定义一个可观察的 属性:

AuthService.ts

isAuthorized() {
    ...
    this.isAuthorized.next(true);
}
isAuthorized$ = this.isAuthorized.asObservable();

这样,属性 将通过执行以下操作在您的主模板中自动更新:

app.component.ts

authService.isAuthorized$.subscribe((response) => {
    this.isAuthorized = response;
});

然后你可以在你的主模板上使用:

app.component.html

<div *ngIf="isAuthorized" ; else showLogin">

并且为了处理可能的等待,正如 AJT_82 已经评论的那样,最好在调用完成之前放置一个微调器。