【发布时间】:2023-01-07 01:32:14
【问题描述】:
我的代码很简单,我的组件中有这个 html
<h2>{{username}}</h2>
<h2>{{sessionId}}</h2>
这是我用来更新这些变量的脚本
//i check for when the router redirects to the /user component
router.events.pipe(
filter((e: Event): e is RouterEvent => e instanceof RouterEvent)
).subscribe(() => {
//router event happens
if (location.path() == "/user") {
//I do a call to the backend to get the user info I need
let userTemp = <string>sessionStorage.getItem("username");
const params = new HttpParams()
.set('username', userTemp);
//the call happens in the service calss that I inject
this.service.getUserInfo(params);
//all it does is getting the data and sessionStorage.setItem() on both values
this.username = <string>sessionStorage.getItem("username");
this.sessionId = <string>sessionStorage.getItem("sessionId");
}
});
即使我先设置值然后获取它们,html 中也只显示用户名变量,不会在 <h2></h2> 标记之间绘制 sessionId 变量。这可能是因为我在 sessionStorage 中已经有了“用户名”值。
注意:两个变量在类中都设置为“null”
这是服务:
getUserInfo(params: HttpParams) {
this.http.get<UserData>('/api/getuserinfo', { params, responseType: 'json' }).subscribe(response => {
//I set the username again
sessionStorage.setItem("username", response.username);
//I add a new value called sessionId
sessionStorage.setItem("sessionId", response.sessionId);
});
}
我尝试设置 ngOnInit() 函数以设置初始化值,然后在服务调用后调用 this.ngOnInit() 但即使调用该函数也是如此。代码上的任何变化都没有帮助,而且我没有找到任何可以解释为什么 Angular 看不到变量更新的内容,即使我可以从调试器访问 sessionStorage 对象中的值。
【问题讨论】:
标签: angular angular-services angular-router session-storage