【问题标题】:Angular9 Update variable to show/hide HTML after content is loadedAngular9更新变量以在加载内容后显示/隐藏HTML
【发布时间】:2020-11-17 11:53:10
【问题描述】:

如何在组件加载后显示/隐藏 HTML 内容?

我正在尝试在标题工具栏上显示/隐藏一个按钮,该按钮会根据登录状态而变化。

下面的工具栏组件加载到主页中。由于该组件是在主页上加载的,因此它永远不会再次重新加载。当我登录时,我想相应地显示和隐藏那个 ion-buttons 部分。

登录后,我在工具栏组件类中调用了 getAndSetLogin() 函数,控制台日志显示 loggedIn=true,现在应该隐藏登录部分,但不会显示/隐藏。

工具栏组件 HTML

<ion-header>
  <ion-toolbar>
    // Hide this button if logged in
    <ion-buttons *ngIf="!loggedIn" slot="end">
      <ion-button (click)="showLoginPopover($event)">
        <ion-label class="header-toolbar-text btn-label">Log In</ion-label>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

(Toolbar Component.ts) 更新工具栏组件登录状态的函数

  public getAndSetLoginState() {
    this.userService.checkedLoggedInStatus().subscribe((loggedInState: any) => {
      // loggedInState is either true or false, true if logged in and false otherwise
      this.loggedIn = loggedInState;
    });
  }

工具栏组件文件中的上述代码在我登录时触发,现在它只是提供程序中的一个按钮,它设置返回一个可观察的 true。

我尝试添加类似的 ChangeDetectorRef

  // Get an observable of the login state
  public getAndSetLoginState() {
    this.userService.checkedLoggedInStatus().subscribe((loggedInState: any) => {
      this.loggedIn = loggedInState;
      this.cd.markForCheck();
      // cd = ChangeDetectorRef initliased in the constructor
    });
  }

但这也没有检测到我的更改。

我是否更正了 Angular 只加载 HTML 一次,正因为如此,ngIf 语句只有在您在 onInit 或构造函数中更改它们时才有效。

如何根据登录状态显示/隐藏内容。我听说过使用 RXJS BehaviourSubject,但不确定这会有什么帮助。

【问题讨论】:

    标签: html angular typescript ionic-framework ionic5


    【解决方案1】:

    您需要为此创建一个 Observable。创建一个 UserService 服务类并在其中创建 BehaviourSubject 对象。设置成功登录时的值。

    像这样:

    import { Injectable } from '@angular/core';
    import { Observable, BehaviorSubject } from 'rxjs';
    
    @Injectable({
        providedIn: 'root'
    })
    export class UserService {
        private isLoggedIn: BehaviorSubject<boolean>;
        constructor() {
            this.isLoggedIn = new BehaviorSubject<boolean>(false);
        }
        
        setUserLoggedInStatus(value) {
            this.isLoggedIn.next(value);
        }
    
        getUserLoggedInStatus(): Observable<any> {
            return this.isLoggedIn.asObservable();
        }
    }
    

    现在在您的组件类中,订阅 getUserLoggedInStatus() 函数,如下所示:

    import { Component, OnInit } from '@angular/core';
    import { UserService } from '@app/shared/services/user.service';
    
    @Component({
      selector: 'app-header',
      templateUrl: './header.component.html',
      styleUrls: ['./header.component.scss']
    })
    export class HeaderComponent implements OnInit {
      isLoggedIn: Boolean;
      constructor(private userService: UserService) { }
    
      ngOnInit() {
        this.userService.getUserLoggedInStatus().subscribe((status)==> {
            this.isLoggedIn = status;
        });
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以将 loggedInState 保存在您的 UserService 文件中。

      export class UserService{
          private logingData;
          private loggedIn = false;
      
        constructor(
          private http: HttpClient,
        ) { }
      
        login(){
          this.logingData= this.http.post(-call your server-);
          return this.logingData;
          this.loggedIn = this.logingData.status;
        }
      }
      

      然后将该 loggedIn 变量绑定到工具栏。

      在 html 中

      <ion-buttons *ngIf="!userService.loggedIn" slot="end">
      

      在ts中

      import { UserService} from "your location";
      
      constructor(public userService: UserService){}
      

      然后从 Popover 组件中调用这个方法。

      public getAndSetLoginState() {
         this.userService.checkedLoggedInStatus().subscribe((loggedInState: any) => {
             console.log(loggedInState);
         });
      }
      

      希望对您有所帮助。谢谢。

      【讨论】:

        【解决方案3】:

        在这种情况下使用BehaviourSubject

        服务文件:

        import { Observable, BehaviorSubject } from 'rxjs';
         export class UserService {
           private isLoggedIn: BehaviorSubject<boolean>(false);
           private _isLoggedIn$ = new BehaviorSubject<boolean>(false);
           readonly isLoggedIn$ = this._isLoggedIn$.asObservable();
             
           getLoggedInStatus(): Observable<any> {
               return this.http.get<any>(url, params).pipe(
                  map((res) => {
                    this._isLoggedIn$.next(res);
                     ..... // other logics here
               })
             );
            }
          }
        

        组件:

        loggedInState$:Observable<any>;
        this.loggedInState$ = this.userService.isLoggedIn$();
        

        HTML:(使用异步管道)

        <ion-buttons *ngIf="!loggedInState | async" slot="end">
        

        【讨论】:

        • this.userService.isLoggedIn$();不是可调用函数,在 html 中,它提到 aysnc 不能分配给 loggedInState,因为它是 null。
        【解决方案4】:

        S Rana 的回答几乎可以正常工作,我正在发布更改以使其正常工作

        服务文件:

        import { Observable, BehaviorSubject } from 'rxjs';
                export class UserService {
                  private isLoggedIn: BehaviorSubject<boolean>(false);
                  private _isLoggedIn$ = new BehaviorSubject<boolean>(false);
                  isLoggedIn$ = this._isLoggedIn$.asObservable();
                    
                  getLoggedInStatus(): Observable<any> {
                      return this.http.get<any>(url, params).pipe(
                         map((res) => {
                           this._isLoggedIn$.next(res);
                            ..... // other logics here
                      })
                    );
                   }
                 }
        

        组件:

        loggedInState$:Observable<boolean>;
        
        this.userService.loggedInChanged$.subscribe((data: any) => {
          this.loggedInState$ = data;
          }
        );
        

        HTML:

        <ion-buttons *ngIf="!loggedInState$" slot="end">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多