简体   繁体   English

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

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

I want to change an HTML view via *ngIf , based on a local variable, which should change based on a variable delivered through an observable from a shared service.我想基于局部变量通过*ngIf更改 HTML 视图,该局部变量应根据通过共享服务的可观察对象传递的变量进行更改。

HTML HTML

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

TypeScript of same component: 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);
  }
} 

TypeScript of shared service AuthService :共享服务 AuthService 的AuthService

export class AuthServiceService {
  isAuthenticated: boolean;

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

While debugging I found out, the variable isAuthenticated in the LoginComponent does not change, on changes of the variable isAuthenticated of the AuthService.在调试时我发现,LoginComponent 中的变量isAuthenticated并没有改变,而 AuthService 的变量isAuthenticated发生了变化。 I also tried using pipe() and tap() , which did not change anything.我也尝试使用pipe()tap() ,这并没有改变任何东西。

What am I doing wrong?我究竟做错了什么?

Convert your AuthServiceService to have the authentication state as a BehaviorSubject and return it as Observable as described below.将您的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();
  }
}

The actual subscription of your observable will only happens once, when the OnInit lifecycle hook is triggered when the component is initialized.当组件初始化时触发OnInit生命周期挂钩时,您的 observable 的实际订阅只会发生一次。

You can subscribe to a BehaviorSubject in order to catch value changes.您可以订阅BehaviorSubject以捕获值更改。

Stackblitz example Stackblitz 示例

AuthService身份验证服务

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

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

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

Component零件

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);
  }
}

Template模板

<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.

相关问题 Angular2订阅全局变量 - Angular2 Subscribe to a global variable 在不使用选择器的情况下在另一个组件中使用局部组件变量 - use a local component variable in another component without using selector 从其他组件更改变量值-Angular 4 - Change variable value from different component - Angular 4 在 Angular 中从一个组件更改另一个组件中的变量 - Changing a variable from one component in another component in Angular 在没有组件Angular2 +的模板html中使用局部变量 - Use local variable in template html without component Angular2+ 有没有办法在另一个组件中使用变量 Angular 组件,并将数据传递给该变量组件? - Is there a way to use a variable Angular component inside another component, and also pass data to that variable component? 变量中的组件选择器 - Angular 2 - Component selector in variable - Angular 2 使用 ngmodel 将一个组件中的变量值获取到另一个组件 - Get value of a variable in one component to another component using ngmodel 单击按钮时将角度传递输入变量传递给另一个组件 - Angular pass input variable to another component on button click 淘汰赛:将可观察对象克隆到另一个变量中并将其变为不可观察 - Knockout: Clone observable object into another variable and turn it not observable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM