繁体   English   中英

将局部变量值订阅到 Angular 中另一个组件中的变量的 Observable

[英]Subscribe a local variable Value to an Observable of variable in another Component in Angular

我想基于局部变量通过*ngIf更改 HTML 视图,该局部变量应根据通过共享服务的可观察对象传递的变量进行更改。

HTML

<div class="login-container" *ngIf="!isAuthenticated">

TypeScript 相同组件:

export class LoginComponent implements OnInit {
  authenticationsSubscription;
  isAuthenticated: boolean;

  constructor(
    private authService: AuthServiceService,
    private router: Router,
    private route: ActivatedRoute){}

  getAuth(): Observable<boolean>{
    return this.authService.validation();
  }

  ngOnInit() {
    this.authenticationsSubscription = this.authService.validation().subscribe(auth => this.isAuthenticated = auth);
  }
} 

共享服务 AuthService 的AuthService

export class AuthServiceService {
  isAuthenticated: boolean;

  validation(): Observable<boolean>{
    return of(this.isAuthenticated);
  }
}

在调试时我发现,LoginComponent 中的变量isAuthenticated并没有改变,而 AuthService 的变量isAuthenticated发生了变化。 我也尝试使用pipe()tap() ,这并没有改变任何东西。

我究竟做错了什么?

将您的AuthServiceService转换为将身份验证 state 作为BehaviorSubject并将其作为Observable返回,如下所述。

import { Observable, BehaviorSubject } from "rxjs";

export class AuthServiceService {
  private isAuthenticatedSub: BehaviorSubject<boolean> = new BehaviorSubject(false);

  set isAuthenticated(isAuthenticated: boolean) {
    this.isAuthenticatedSub.next(isAuthenticated);
  }

  get isAuthenticated(): boolean {
    return this.isAuthenticatedSub.value;
  }

  validation(): Observable<boolean> {
    return this.isAuthenticatedSub.asObservable();
  }
}

当组件初始化时触发OnInit生命周期挂钩时,您的 observable 的实际订阅只会发生一次。

您可以订阅BehaviorSubject以捕获值更改。

Stackblitz 示例

身份验证服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class AuthService {
  isAuthenticated: BehaviorSubject<boolean>;

  constructor() {
    this.isAuthenticated = new BehaviorSubject<boolean>(false);
   }
}

零件

import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  isAuthenticated: Observable<boolean>;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.isAuthenticated = this.authService.isAuthenticated;
  }

  login() {
    this.authService.isAuthenticated.next(true);
  }

  logout() {
    this.authService.isAuthenticated.next(false);
  }
}

模板

<div *ngIf="isAuthenticated | async; else notAuthenticated">
  User is authenticated
  </div>

  <ng-template #notAuthenticated>
  <div>User isn't authenticated</div>
  </ng-template>

  <button (click)="login()">Login</button>
  <button (click)="logout()">Logout</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM