无法使用主题订阅更改角度组件中的类字段

问题描述 投票:0回答:1
import { Component, OnInit } from '@angular/core';
import { AuthDataService } from '../Service/authDataService';
import { map } from 'rxjs';
import { User } from '../Model/userModel';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-success',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './success.component.html',
  styleUrl: './success.component.css',
})
export class SuccessComponent implements OnInit {
  authenticated = false;

  constructor(private authService: AuthDataService) {}

  ngOnInit(): void {
    this.authService.userSubject.subscribe((user) => {
      console.log(user);
      this.authenticated = !!user;
      console.log('In the body of subscribe');
      //true here
      console.log(this.authenticated);
    });
    //still false
    console.log('outside');
    console.log(this.authenticated);
  }

  check() {
    //false here to
    console.log(this.authenticated);
  }
}

我正在尝试使用订阅将用户对象的更改发送到我的所有组件...但即使在发出更改后,它似乎也没有更改布尔值...

angular typescript rxjs
1个回答
0
投票

订阅内部的代码称为异步代码,与同步代码不同,异步代码发生在稍后的时间点,它等待事件发生,但其下面的代码不会等待订阅完成,所以要处理这个问题,您需要移动您希望在订阅内进行身份验证后发生的逻辑

  ngOnInit(): void {
    this.authService.userSubject.subscribe((user) => {
      console.log(user);
      this.authenticated = !!user;
      console.log('In the body of subscribe');
      //asynchronous move all your logic inside here!
      console.log(this.authenticated);
    });
    // synchronous does not wait for subscribe to complete
    console.log('outside');
    console.log(this.authenticated);
  }
© www.soinside.com 2019 - 2024. All rights reserved.