代码之家  ›  专栏  ›  技术社区  ›  Anuj TBE

通过应用程序在角度上更新特定项目的本地存储值

  •  0
  • Anuj TBE  · 技术社区  · 6 年前

    我在用 Angular 6

    在进行用户身份验证的登录方法中。我叫服务 auth

    这就是我的登录方法

    loginUser() {
        const email = this.loginForm.value.username;
        const password = this.loginForm.value.password;
    
        this.auth.getAuthToken(email, password).subscribe(response => {
    
            // User is authenticated, save response access token credentials
            // in local storage using Auth Service
            this.auth.setCredentials(response);
    
            /**
             * Get user profile
             */
            this.account.getProfile().subscribe(
                res => {
                    // Store user info to local storage
                    this.auth.setProfileInfo(res);
                }
            );
    
            this.router.navigate(['dashboard']).then();
    
        });
    }
    

    现在,我有几个其他的组件可以让登录的用户更改他的个人资料信息,比如不同的组件可以更改头像,另一个组件可以更改名字等等。

    在每个组件中,我都使用存储在本地存储器中的值来显示在UI中。

    但每当配置文件信息被更改时,我需要手动将更新的配置文件信息存储到本地存储中,以便它可以反映到任何地方。

    编辑2

    0 回复  |  直到 6 年前
        1
  •  0
  •   Ales    6 年前

    如何从本地存储访问数据?正常的本地存储数据只是在用户重新打开应用程序时保存数据。否则,您将其保留在服务中,一旦服务中的值发生更改,您将在本地存储中应用该值(但只是将其备份,而不是不断地从中读取)。

    我用观测数据解决了这个问题。

    @LocalStorage()
    storageValue: YourData;
    
    profileChanged$ = new BehaviorSubject(true);
    
    userProfile$ = profileChanged$.pipe(
      startWith(this.storageValue)
      switchMap(() => getDataObservable()),
      tap(res => this.storageValue = res)
      share()
    );
    
    // and then in login
    login() {
      // PREVIOUS AUTH
      
      this.profileChanged$.next(true);
    
    }

    您可以订阅要在组件中使用异步管道或订阅来显示的可观察数据。

    https://www.npmjs.com/package/ngx-webstorage

    基本上这就是:

    1. 保存本地存储值的值-storageValue
    2. triggerObservable到refetch数据
    3. cold and hot observables )