无法检索可观察的数据

时间:2017-02-14 18:12:06

标签: angular local-storage

这是我在Angular2中的本地存储服务类。

import { Injectable } from '@angular/core';
import { isBrowser, isNode } from 'angular2-universal';
import { Observer, Observable, Subject } from 'rxjs/Rx';
import { WindowRefService } from './window';

@Injectable()
export class LocalStorageService {
    private data: any;

    constructor(private window: WindowRefService) {}

    write(key: string, value: any) {
        if (value) {
            value = JSON.stringify(value);
        }

        if (isBrowser) {
            this.window.nativeWindow.localStorage.setItem(key, value);
        }
    }

    read(key: string): Observable<any> {
        if (isBrowser) {
            let value: string = this.window.nativeWindow.localStorage.getItem(key);

            if (value && value !== 'undefined' && value !== null) {
                this.data = JSON.parse(value);
            }
        }

        let subject = new Subject();
        subject.next(this.data);
        subject.complete();

        return Observable.from(subject);
    }

    delete(key: string) {
        if (isBrowser) {
            this.window.nativeWindow.localStorage.removeItem(key);
        }
    }
}

我正在尝试访问NavMenuComponent类中的localStorageService。

import { Component, OnInit } from '@angular/core';
import { LocalStorageService } from '../../services';

@Component({
    selector: 'nav-menu',
    template: require('./navmenu.component.html'),
    styles: [require('./navmenu.component.css')]
})
export class NavMenuComponent {
    isAnonymous: boolean = true;
    isAdmin: boolean = false;
    isTalent: boolean = false;
    isEmployer: boolean = false;

    constructor(private ls: LocalStorageService) {
    }

    ngOnInit() {
        // check local storage if logged in
        this.ls.read('user').subscribe(result => this.localStorageChange(result));
    }

    localStorageChange(user: any) {

        if (user && typeof user !== 'undefined') {
            this.isAdmin = user.isAdmin;
            this.isEmployer = user.isEmployer;
            this.isTalent = user.isTalent;
            this.isAnonymous = false;
        } else this.isAnonymous = true;

    }
}

我无法成功订阅我的观察。我猜这与我的服务有关。我画了一个空白。非常感谢任何帮助!

0 个答案:

没有答案