angular - Angular:无法从单例服务实例中获取更新的数据
问题描述
注意:使用 Angular 10.2,节点 12.16.3
背景:
我有一个身份验证服务声明为单例app.module.ts
:
@NgModule({
...
providers: [
AuthGuardService,
--> AuthService,
HouseService,
...
为了让我的问题保持简单,我只需要更新身份验证服务中的一个局部变量,并使其可用于降级服务。
问题:
其他组件(即NavbarComponent
)访问此数据的每一次尝试和方法都只返回它最初是如何初始化的。
尝试的解决方案:
- 看起来像是服务实例化问题,但上面的代码应该表明身份验证服务是整个模块的单例。
- 根据另一个 StackOverflow 帖子,我添加了
--aot
ng build 命令。 - 根据其他 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(...)
,我现在会看到正在进行更改的(预期的)消息;但是,我的接收函数BehaviorSubject
是OLD值。
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
我已经为此花费了几天时间,因此非常感谢任何建议和/或指导。
更多细节基于评论
- (app)/home/login-form 组件调用 AuthenticationService.login():
onSubmit() {
this.submitted = false;
this.authSrv.login(this.modelUsername, this.modelPassword).subscribe(
() => {
this.router.navigateByUrl('/');
},
...
出于测试目的,登录方法现在只调用changeMessage(...)无济于事。
- 更新了顶级注释以反映节点版本 (12.16.3)
解决方案
如上述评论所述,该问题是对较低级别组件中的身份验证服务的额外引用(不仅仅是在 app.module.ts 中)。归功于安德鲁·奥尔德森(Andrew Alderson)的轻推检查!!!
推荐阅读
- javascript - 创建元素后如何执行函数
- java - 如何从 Java 调用具有自定义复杂对象类型作为输入参数的 Oracle PL-SQL 过程
- docker - Docker 版本控制在 Ubuntu 和 CentOS 上是不同的
- ruby-on-rails - 在其他字段上触发验证时复选框未保持选中状态
- json - 仅使用 Angular 7 将 json 数据写入本地 JSON 文件
- google-apps-script - 比较两列的匹配项并拉取每个匹配项的相邻值
- c# - 如何在没有 API 的情况下获取 Instagram 页面的关注者数量
- javascript - 使用 [FromForm] 属性时,集合始终为空
- regex - 匹配浮点数的任务
- javascript - 如何在 setInterval 方法中获取更新的会话变量