我向Angular2站点添加功能以显示当前登录用户的名称。无限HTTP请求订阅可观察到的后端
我似乎能够从后端服务检索我需要的信息。但是,当正在运行的前端代码正在运行时,只有一个请求需要时,才会反复发送对后端的请求并尽可能快地发送。
当我更改代码以订阅observable时,开始了无限循环的请求。在没有订阅的情况下,我能够从前端服务中获取的信息不可用;它看起来像下面的例子。
{"_isScalar":false,"source":{"_isScalar":false},"operator":{}}
组件
loggedInUser() {
this.authService.loggedInUser().subscribe(res => {
this.currentUser = res;
return this.currentUser;
})
}
前端服务
loggedInUser() {
const userId = localStorage.getItem('userId');
return this.http
.get('http://localhost:3000/user/current/' + userId)
.map((response: Response) => {
const user = response.json();
return user;
})
我了解到,这并不是真正意义上的 “无限循环” 从堆栈溢出阅读其他职位。但是,我无法理解那些其他职位的解决方案。
谢谢您的帮助!