我正在使用GlobalDataService
(referred from here)来存储来自登录API的响应数据,以用于其他一些API调用。
登录():
if (_token) {
// store username and jwt token in keep user logged in between page refreshes
console.log(this.gd.currentUserData)
this.gd.currentUserData['userID']=_id;
this.gd.currentUserData['username']=username;
this.gd.currentUserData['token']=_token;
// return true to indicate successful login
return true;
}
然后在xx.service.ts
文件中,我正在访问这个全局变量,如下面constructor()
中所示,然后由各种函数使用它来进行API调用。
constructor(private http: Http, private gd: GlobalDataService) {
let currentUser = this.gd.currentUserData;
this.token = currentUser && currentUser.token;
this.userID=currentUser.userID;
}
问题
在我注销(在此期间清除全局变量中的数据)然后使用其他用户帐户登录后,service.ts
中的函数仍在使用存储在这些全局变量中的先前数据。
在logout()中:
this.gd.currentUserData={};
this.gd.currentHospitalData={};
我认为问题是构造函数只被实例化一次,因此分配给全局变量的新数据没有反映在.service.ts
文件中。
如何解决此问题?或者有更好的方法来处理这种情况吗?
注意:之前我使用localstorage
来存储这些数据,但由于可以通过Chrome Dev Tools进行修改,我现在正在考虑使用全局变量。
更新
我知道这是hacky而不是正确的方法,但我注意到在logout()上调用 window.location.reload();
解决了这个问题。
显然,这个问题似乎已经解决了。我必须将我的服务的提供者声明从app.module.ts
移到应用程序组件中的较低级别,然后成功登录重定向到。
但我仍然在寻找适当的解决方案/方法来处理登录数据。
答案 0 :(得分:4)
真正的问题是我在.service.ts
内为我的app.mopdule.ts
申报了提供商。这导致这些服务的构造函数仅在首次加载应用程序时才实例化。因此,当我退出并再次登录时,新分配的数据未反映在.service.ts
个文件中,
我将这些服务的Provider声明移动到成功登录后重定向到的组件。现在,每次成功登录后,构造函数都将实例化,新分配的值将在这些.service.ts
文件中重新生成。
答案 1 :(得分:1)
“全局变量”也可以通过Chrome开发工具进行修改。但这有点困难。
如果您的数据不敏感,那么您不必担心,您可以将它存储在任何地方,无论您想要什么。
正如您所说,您的问题是构造函数只被调用一次。因为服务是单身,这意味着整个会话中只有一个且只有一个实例。
要解决此问题,您有以下几种选择: