[英]Angular: Can't Get Updated Data out of Singleton Service Instance
注意:使用 Angular 10.2,节点 12.16.3
背景:我在 app.module.ts 中有一个身份验证服务声明为app.module.ts
:
@NgModule({
...
providers: [
AuthGuardService,
--> AuthService,
HouseService,
...
为了让我的问题保持简单,我只需要更新身份验证服务中的一个局部变量,并使其可用于降级服务。
问题:其他组件(即NavbarComponent
)访问此数据的每一次尝试和方法都只返回它最初的初始化方式。
尝试的解决方案:
--aot
添加到 ng build 命令。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);
})
...
}
当前(控制台)结果:如果我在login()
中删除对changeMessage(...)
的调用,组件会收到更改通知(尽管我认为这主要是初始化事件):
ComponentA: Update event captured: new message=ORIGINAL MESSAGE
ComponentA: Message value is now=ORIGINAL MESSAGE
如果我离开对changeMessage(...)
的调用,我现在会看到正在进行更改的(预期的)消息; 但是,我收到的BehaviorSubject
的 function 是旧值。
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
我已经为此花费了几天时间,因此非常感谢任何建议和/或指导。
更多细节基于评论
onSubmit() {
this.submitted = false;
this.authSrv.login(this.modelUsername, this.modelPassword).subscribe(
() => {
this.router.navigateByUrl('/');
},
...
出于测试目的,登录方法现在只调用changeMessage(...)无济于事。
如上述评论所述,该问题是对较低级别组件中的身份验证服务的额外引用(不仅仅是在 app.module.ts 中)。 归功于安德鲁·奥尔德森(Andrew Alderson)的轻推检查!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.