本文介绍了本地存储更改时rxjs可观察到的角度2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可观察变量,该变量在对localStorage变量进行更改时会返回值.我的订户在对localStorage进行更改(或就此而言为内存变量)后未获得新值.

I am trying to create an observable that returns values when changes to a localStorage variable happens. My subscriber is not getting the new values upon changes to localStorage (or for that matter an in memory variable).

    import { Component, OnInit } from '@angular/core';
    import { UserService } from '../services/user.service';

    /**
     * This class represents the navigation bar component.
     */
    @Component({
      moduleId: module.id,
      selector: 'sd-navbar',
      templateUrl: 'navbar.component.html',
      styleUrls: ['navbar.component.css'],
      providers: [UserService]
    })

    export class NavbarComponent implements OnInit {
      loggedIn: boolean;
      constructor(private us: UserService) { }

      ngOnInit() {
        this.us.isLoggedIn().subscribe(loggedIn => {
          this.loggedIn = loggedIn;
        });
      }
    }

auth.component.ts

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    import { UserService } from '../shared/services/user.service';

    /**
     * This class represents the lazy loaded AuthComponent.
     */
    @Component({
      moduleId: module.id,
      selector: 'sd-auth',
      templateUrl: 'auth.component.html',
      styleUrls: ['auth.component.css'],
      providers: [UserService]
    })
    export class AuthComponent implements OnInit {
      authParams = {
        provider: '',
        params: {}
      };

      constructor(private route: ActivatedRoute, private us: UserService) { }
      ngOnInit() {
        this.route.params.forEach((param) => {
          this.authParams.provider = param.authprovider;
        });

        this.route.queryParams.forEach((queryParams) => {
          this.authParams.params = queryParams;
        });

        this.us.logIn("google", JSON.stringify(this.authParams));

        console.log(JSON.parse(localStorage.getItem('authParams')));

      }
    }

user.service.ts

    // user.service.ts
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { Subscriber } from 'rxjs/Subscriber';

    @Injectable()
    export class UserService {
      private loggedIn = false;
      private logger = new Observable<boolean>((observer: Subscriber<boolean>) => {
        observer.next(this.loggedIn);
      });
      constructor() {
        if (localStorage.getItem('authParams')) {
          this.loggedIn = !!JSON.parse(localStorage.getItem('authParams')).params.id_token;
        } else {
          this.loggedIn = false;
        }
      }

      logIn(provider: string, providerResponse: string) {
        localStorage.setItem('authParams', providerResponse);
        this.loggedIn = true;
      }

      isLoggedIn(): Observable<boolean> {
        return this.logger;
      }

      logOut() {
        localStorage.removeItem('authParams');
        this.loggedIn = false;
      }
    }

流看起来像

第1步-导航栏订阅UserService(获取默认值loggingIn = false)第2步-AuthComponent更新UserService(设置登录状态= true)

Step 1- Navbar subscribes to UserService (Gets the default value of loggedIn=false)Step 2 - AuthComponent updates UserService (sets loggedIn = true)

我在Navbar中的订阅未更新.我在这里想念什么.我是否需要在UserService的logIn方法中放入诸如事件发射器之类的内容?

My subscription in Navbar is not getting updated. What am I missing here. Do I need to put something in the logIn method of UserService like event emitter?

推荐答案

您想要的是一个主题.在此处中查看文档.

What you want is a Subject. Check out the docs here.

举个简单的例子,像这样:

For a quick example, something like this:

export class UserService {
  ...
  private logger = new Subject<boolean>();
  ...

  isLoggedIn(): Observable<boolean> {
    return this.logger.asObservable();
  }

  logIn(provider: string, providerResponse: string) {
    localStorage.setItem('authParams', providerResponse);
    this.loggedIn = true;
    this.logger.next(this.loggedIn);
  }

  logOut() {
    localStorage.removeItem('authParams');
    this.loggedIn = false;
    this.logger.next(this.loggedIn);
  }
...

这篇关于本地存储更改时rxjs可观察到的角度2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 12:09