对角度避免位置中的组件变化做出反应。reload()

时间:2020-10-16 16:35:00

标签: angular service

在这个简单的应用程序中,我在角度构建时遇到了美学问题,导致我每次对登录或注册组件进行更改时都会更改用户的身份验证状态,应用程序中的其他组件在重新加载该组件之前不会监听它带有功能reload()的页面。

让我们说我的服务中有一个登录功能,该功能一旦通过身份验证即可将用户设置在我的本地存储中。然后通过此服务,其他组件将基于经过身份验证的用户来更新或公开信息

AuthService

signIn(signedinUser: SignInModel) {//SigInModel is a predesigned model 
    return this.httpClient.post<any>(`/signin`, signedinUser).pipe(
      map((userData) => {
        console.log(userData);
        ...some code...
        sessionStorage.setItem('username', signedinUser.username);
        return userData;
      })
    );
  }

isUserLoggedIn() {
    let user = sessionStorage.getItem('username');
   
    return !(user === null);
 }//this method once the logged user is stored in local storage through the action of signing in 
  triggered in the fucntion signIn() return the condition of his existence or not in the 
  local storage, being reference for other components in order to show or not information according 
  with the auth

然后在我的登录组件上

...some code...
   loginUser() {
     this.authService.signIn(this.loginForm.value).subscribe((result) => {
        if (result.error) {
          console.log('Sorry something went wrong ');
        } else {
          this.routerMethod();//routering after login
        }
      });
    }

  async routerMethod() {
    await this.router.navigate(['/']);
    setTimeout(() => {
      location.reload();
    }, 500);//Wrong not aesthetic !!!
  }

从字面上看,我触发登录过程,通过服务中初始化的方法,该方法具有Reactive Form(this.loginForm.value)的所有值作为参数,然后被该方法使用,如果成功,我只是调用路由器方法到另一个组件,该组件显示可用于身份验证的用户可用的所有元素,但是它本身不起作用,因此我必须插入页面重装,以便在路由器行为后提交更改(我猜这是错误的)。

然后在组件中侦听更改,如果用户已通过身份验证或未访问该服务,则我只会在我的本地存储上查看该方法,该方法在检查本地存储是否为空的服务中初始化了


Some Component

isAuth:boolean;

ngOnInit(): void {
    this.isAuth = this.authService.isUserLoggedIn().valueOf();

......do some .....
}

一旦用户登录,我该如何减轻页面加载的负担,同时使所有组件对从服务提交的任何更改做出反应。

提前谢谢!

0 个答案:

没有答案