Angular 4 BehaviorSubject没有正确多播

时间:2017-06-28 09:54:29

标签: html angular typescript rxjs

我有一个保存从服务器收到的用户对象的服务。我希望我的导航栏在存储用户时隐藏“登录”按钮(并在用户被删除时显示)。我写了一个服务,它应该通知所有组件的下载

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { User } from '../models/user';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class MessageService {

  user: User;
  subject = new BehaviorSubject(this.user);

  setUser() {
    console.log('setting user...')
    try {
      var user = JSON.parse(localStorage.getItem('currentUser'));
      this.subject.next(user);
      console.log('setted' + JSON.stringify(user));
    } catch (error) {
      console.log(error);
      this.subject.next(null);
    }

  }

  unsetUser(){
    console.log("Current user was' " + this.subject);
    localStorage.removeItem('userToken');
    localStorage.removeItem('currentUser');
    this.subject.next(null);
  }

}

以及订阅他的导航栏组件

import { Component } from '@angular/core';
import { User } from '../models/user';

import { Subscription } from 'rxjs/Subscription';
import { MessageService } from '../services/message.service';

@Component({
  selector: 'nav-comp',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css'],
  providers: [ MessageService],
})
export class NavComponent {

  public currentUser: User;
  subscription: Subscription;

  constructor(
    private messageService: MessageService, ) {
    this.subscription = messageService.subject.subscribe({
      next: (User) => this.currentUser = User });
    console.log('received: ' + this.currentUser);
  }

  quit() {
    console.log("performing logout...");
    this.messageService.unsetUser();
  }

}
<nav class="white" role="navigation">
  <div class="nav-wrapper container">
    <ul class="left hide-on-med-and-down">
      <li><a routerLink="/home" routerLinkActive="active" id="logo-container" href="#" class="brand-logo">Skoob</a></li>
    </ul>
    <ul class="right hide-on-med-and-down">
      <li *ngIf="currentUser==null"><a class=" btn-flat" routerLink="/signup" routerLinkActive="active">registrati </a></li>
      <li *ngIf="currentUser==null"><a class=" btn-flat" routerLink="/login" routerLinkActive="active">accedi</a></li>
      <li *ngIf="currentUser!=null"><a class=" btn-flat" (click)="this.quit()" routerLinkActive="active">logout</a></li>
      <li *ngIf="currentUser!=null"><a class="btn-flat">dashboard</a></li>
    </ul>

    <ul id="nav-mobile" class="side-nav cyan">
      <li><a class=" btn">Button <i class="material-icons right">cloud</i></a></li>
    </ul>
    <a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
  </div>
</nav>

navbar仅在启动时收到未定义,但不再是

更新: 如果我检查this.subject.value它有正确的值,但导航栏不知道......

1 个答案:

答案 0 :(得分:3)

问题是,您在组件级别提供服务:

@Component({
  selector: 'nav-comp',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css'],
  providers: [ MessageService], // here!
})

这意味着该组件拥有自己的服务实例。所以它根本不是共享服务。这就是为什么您的组件只获得user的初始值undefined,但该值永远不会再次更改,因为这是一个完全独立的服务实例。

要实际拥有共享服务,您需要在模块级别提供服务:

@NgModule({
....
providers: [MessageService]
})

并从组件中删除所有providers数组!