菜单Angular 8中的用户登录/注销按钮未更新 [英] User login/logout button in menu Angular 8 not updating

查看:77
本文介绍了菜单Angular 8中的用户登录/注销按钮未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有登录/注销按钮的mat-toolbar,网站用户可以随时登录或注销.我有一个身份验证服务,该服务使用用户数据创建一个Observable,并使用*ngIf="!(authService.user$ | async)作为登录按钮.但是,除非我手动刷新整个页面,否则这将无法正常工作.为什么会这样?对此有何作用?我以为Observable会在这些情况下实际起作用,但是显然我缺少了一些东西.

I have a mat-toolbar with a login/logout button where the user of the website can login or out at all times. I have an authentication service which creates an Observable with user data and using *ngIf="!(authService.user$ | async) for the login button. This isn't working though, unless I manually refresh the whole page. Why is this and what does one do about it? I thought the Observable would be a way that would actually work in these situations, but obviously I am missing something.

我还尝试在 app.component.ts 中将Observable订阅为user,并在模板中使用user,但这似乎无济于事.我知道有一些关于用户使用Observables登录的问题,以及有关刷新的问题,但是它们并没有使我理解为什么它不起作用.

I have also tried subscribing to the Observable as user in app.component.ts and using user in the template, but this doesn't seem to help. I know there are several questions regarding user login with Observables, and questions about refresh, but they haven't given me an understanding of why this isn't working.

我也许应该补充一点,我正在使用具有属性roles的接口User进行基于角色的授权,因此它与firebase.User不同.

I should perhaps add that I am using an interface User with property roles, for role based authorisation, so it is not the same as firebase.User.

authentication.service.ts 的相关部分:

@Injectable({
  providedIn: 'root'
})

export class AuthenticationService {
  user$: Observable<User>;
  viewAllUser: Boolean = false;

  constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`Users/${user.uid}`).valueChanges()
        } else {
          return of(null)
        }
      }))
  }

  /* Sign up */
  SignUp(email: string, password: string) {
    this.afAuth.auth.createUserWithEmailAndPassword(email, password)
      .then((result) => {
        window.alert("You have been successfully registered!");
        this.updateUserData(result.user)
        //console.log(result.user);
      }).catch((error) => {
        window.alert(error.message);
        //console.log(error.user);
      });
  }

  /* Sign in */
  SignIn(email: string, password: string) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        window.alert("You have been successfully signed in!");
        this.updateUserData(result.user);
        //console.log(result.user);
      }).catch((error) => {
        window.alert(error.message);
        //console.log(error.user);
      });
  }

  /* Sign out */
  SignOut() {
    this.router.navigate(['user-main']);
    this.afAuth.auth.signOut();
    window.alert("You have been successfully signed out!");
  }

 private updateUserData(user) {
        // Sets user data to firestore on login
        const userRef: AngularFirestoreDocument<any> = this.afs.doc(`Users/${user.uid}`);
        const data: User = {
          uid: user.uid,
          email: user.email,
          roles: {
            role1: true //default role
          }
        }
        return userRef.set(data, { merge: true }) //Update in non-destructive way 
      }
}

app.component.html:

<body>
  <mat-toolbar>
    <span>
      <button mat-menu-item *ngIf="!(authService.user$ | async) as user" routerLink="/user-main">Login</button>
      <button mat-menu-item (click)="authService.SignOut()" routerLink="/user-main" *ngIf="authService.user$ | async">Logout</button>
      {{user.email}} //for testing
    </span>
    <span>
      <button mat-icon-button [matMenuTriggerFor]="appMenu">
        <mat-icon>more_vert</mat-icon>
      </button>
    </span> 
  </mat-toolbar>
  <mat-menu #appMenu="matMenu">
    <!-- Only to be shown to logged in users: -->
    <button mat-menu-item *ngIf="authService.user$ | async" routerLink="/user-main">User main</button>
    <button mat-menu-item *ngIf="authService.user$ | async" routerLink="/page_x">Page X</button>
    <button mat-menu-item *ngIf="authService.canViewData(authService.user$ | async)==true" routerLink="/secret_page_y">Secret page Y</button>
  </mat-menu>

  <!--This is where the routes are shown-->
  <router-outlet></router-outlet>
</body>

app.component.ts:

import { Component } from '@angular/core';
import { AuthenticationService } from './shared/authentication.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user;

  constructor(public authService: AuthenticationService) {
    this.authService.user$.subscribe(user => this.user = user);
  }
}

推荐答案

您应该为用户使用BehaviorSubject并像这样使用它:

You should use a BehaviorSubject for the user and use it like :

authentication.service.ts:

authentication.service.ts:

    private currentUserSubject = new BehaviorSubject<User>({} as User);
    public currentUser = this.currentUserSubject.asObservable().pipe(distinctUntilChanged());

  getCurrentUser(): User {
    return this.currentUserSubject.value;
  }
      /* Sign up */
      SignUp(email: string, password: string) {
        this.afAuth.auth.createUserWithEmailAndPassword(email, password)
          .then((result) => {
            window.alert("You have been successfully registered!");
            this.updateUserData(result.user);
            //console.log(result.user);
          }).catch((error) => {
            window.alert(error.message);
            //console.log(error.user);
          });
      }

      /* Sign in */
      SignIn(email: string, password: string) {
        return this.afAuth.auth.signInWithEmailAndPassword(email, password)
          .then((result) => {
            window.alert("You have been successfully signed in!");
            this.updateUserData(result.user);
            //console.log(result.user);
          }).catch((error) => {
            window.alert(error.message);
            //console.log(error.user);
          });
      }


      private updateUserData(user) {
        // Sets user data to firestore on login
        const userRef: AngularFirestoreDocument<any> = this.afs.doc(`Users/${user.uid}`);
        const data: User = {
          uid: user.uid,
          email: user.email,
          roles: {
            role1: true //default role
          }
        }
        this.currentUserSubject.next(data); // --> here
        return userRef.set(data, { merge: true }) //Update in non-destructive way 
      }
}

app.component.ts:

app.component.ts:

this.authService.currentUser.subscribe(user => this.user = user);

auth-guard.service.ts:

auth-guard.service.ts:

const user = this.authService.getCurrentUser();
if (user.id) {
   return true;
} else {
   return false;
}

这篇关于菜单Angular 8中的用户登录/注销按钮未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆