首页 > 解决方案 > Angular:无法从单例服务实例中获取更新的数据

问题描述

注意:使用 Angular 10.2,节点 12.16.3

背景: 我有一个身份验证服务声明为单例app.module.ts

@NgModule({
  ...
  providers: [
    AuthGuardService,
--> AuthService, 
    HouseService,
...

为了让我的问题保持简单,我只需要更新身份验证服务中的一个局部变量,并使其可用于降级服务。

问题: 其他组件(即NavbarComponent)访问此数据的每一次尝试和方法都只返回它最初是如何初始化的。

尝试的解决方案:

  1. 看起来像是服务实例化问题,但上面的代码应该表明身份验证服务是整个模块的单例。
  2. 根据另一个 StackOverflow 帖子,我添加了--aotng build 命令。
  3. 根据其他 StackOverflow 帖子,我尝试使用BehaviorSubject在调用登录消息后更新基本消息(字符串)的位置:
@Injectable()
export class AuthService {
  ...
  messageSource = new BehaviorSubject('ORIGINAL MESSAGE');
  currentMessage = this.messageSource.asObservable();
  ...
  changeMessage(message: string) {
    console.log("Authentication Service: changeMessage called with: " + message);
    this.messageSource.next(message);
  }
  ...
  public login(modelUsername: any, modelPassword: any) {
    console.log("Authentication Service: Updating message via changeMessage...");            
    this.changeMessage("UPDATED MESSAGE VALUE");
  }
@Component({
  selector: 'navbar',
  templateUrl: 'navbar.component.html',
  styleUrls: ['./navbar.component.css'],
})
export class NavbarComponent {
  ...
  message:string;
  ...

  ngOnInit() {
    this.authService.currentMessage.subscribe(newMessage => {
      console.log("NavbarComponent : Update event captured: new message=" + newMessage);
      this.message = newMessage;
      console.log("NavbarComponent : Message value is now=" + newMessage);
    })
    ...
  }

当前(控制台)结果:changeMessage(...)如果我删除对in 的调用login(),组件会收到更改通知(尽管我认为这主要是初始化事件):

ComponentA: Update event captured: new message=ORIGINAL MESSAGE
ComponentA: Message value is now=ORIGINAL MESSAGE

如果我在对 的调用中离开changeMessage(...),我现在会看到正在进行更改的(预期的)消息;但是,我的接收函数BehaviorSubjectOLD值。

Authentication Service: Updating message via changeMessage...
Authentication Service: changeMessage called with: UPDATED MESSAGE VALUE
ComponentA: Update event captured: new message=ORIGINAL MESSAGE
ComponentA: Message value is now=ORIGINAL MESSAGE

我已经为此花费了几天时间,因此非常感谢任何建议和/或指导。

更多细节基于评论

  1. (app)/home/login-form 组件调用 AuthenticationService.login():
 onSubmit() {
    this.submitted = false;

    this.authSrv.login(this.modelUsername, this.modelPassword).subscribe(
      () => {
        this.router.navigateByUrl('/');
      },
...

出于测试目的,登录方法现在只调用changeMes​​sage(...)无济于事。

  1. 更新了顶级注释以反映节点版本 (12.16.3)

标签: angularsingleton

解决方案


如上述评论所述,该问题是对较低级别组件中的身份验证服务的额外引用(不仅仅是在 app.module.ts 中)。归功于安德鲁·奥尔德森(Andrew Alderson)的轻推检查!!!


推荐阅读