我有这个组成部分。
constructor(private cs : CredentialsService) {
this.fullname = this.cs.getFullname();
this.address = this.cs.getAddress();
this.telp = this.cs.getTelp();
this.photo = this.cs.getPhoto();
if(this.photo == ""){
this.photo = "https://via.placeholder.com/150x150"
}else{
this.photo = "http://localhost:84/ELEARNINGAPI/upload/" + this.photo
} this.email = this.cs.getEmail();
}
和此服务CredentialsService
(用于存储本地用户信息)。
export class CredentialsService {
credentials : any;
constructor(private apiservice : LoginapiService) {
this.credentials = JSON.parse(this.apiservice.getLogginCredentials());
if(this.credentials == null){
this.apiservice.logout();
}
}
getFullname(){
return this.credentials.fullname;
}
getEmail(){
return this.credentials.email;
}
getAddress(){
return this.credentials.address;
}
getTelp(){
return this.credentials.telpno;
}
getPhoto(){
return this.credentials.profilpict;
}
}
这是我的apiservice.getLogginCredentials()
getLogginCredentials(){
return localStorage.getItem("Credentials");
}
因此,正如您在我的component constructor
中所看到的那样,我从CredientialsService获取了值。这就是我设置CredentialsService的方式
this.loginapi.setLogginCredentials("somejson");
--
setLogginCredentials(UserInfo){
localStorage.setItem("Credentials" , JSON.stringify(UserInfo));
}
我有一个update component
要用新值重新设置setLogginCredentials
。所以我的问题是,当我用新的值更新值时,我仍然需要刷新整个页面来刷新组件构造函数中的值。
答案 0 :(得分:0)
您可以使用反应性方式。订阅可观察/主题,您的组件将自动更新。这是一个示例,根据您的需要进行更改:
import { BehaviorSubject } from "rxjs";
export class Service {
loginCred$: BehaviorSubject<string> = new BehaviorSubject(this.getLogginCredentials());
getLogginCredentials() {
return localStorage.getItem("Credentials");
}
setLogginCredentials(UserInfo) {
const creds = JSON.stringify(UserInfo)
localStorage.setItem("Credentials", creds);
this.loginCred$.next(creds);
}
getCredsSubject() {
return this.loginCred$;
}
}
export class Component {
private creds: string;
constructor(private service: Service) {
service.getCredsSubject().subscribe(creds => {
this.creds = creds;
});
}
}
答案 1 :(得分:0)
触发事件(名为change detection)时,Angular会自动更新视图。这样的异步事件是可观察到的,承诺或超时。
您的代码中的问题是localStorage.setItem
不会触发任何事件。要解决此问题,您可以模拟一个事件,只需将您的setItem
放在 0s 超时之后,或者可以使用angular-local-storage这样的模块来为您做魔术。
在第一种情况下:
setTimeout(() => localStorage.setItem("Credentials" , JSON.stringify(UserInfo)), 0);