Angular 5 Rxjs Subject.subscribe()不会在多个组件中触发

时间:2018-05-13 19:08:55

标签: javascript angular rxjs

我正在使用rxjs和主题来更新我的两个组件。

我正在订阅服务中的主题,但是当在主题上调用.next方法时,它只会更新我的一个组件。

该应用程序包含一个用于初始化websocketconnection的WebsocketService,一个使用WebsocketService连接到后端并发送/接收通知的NotificationService。

我有一个NotificationComponent,我可以在其中创建新通知。在此组件中,我在NotificationService中订阅了Subject,并在更新时显示通知。这很好用,消息到达后端,并在当前有连接的所有浏览器中得到更新。

我的下一步是在HeaderComponent中显示此通知。我在这里注入了NotificationService并订阅了相同的Subject,但是当我发送通知时,HeaderComponents订阅不会触发。 console.log消息永远不会出现在控制台中。

WebSocketService

import { Injectable } from '@angular/core';
import { ReplaySubject, Subject, Observable, Observer } from 'rxjs/Rx';

@Injectable()
export class WebsocketService {

  constructor() { }

  private subject: ReplaySubject<MessageEvent>;

  public connect(url): ReplaySubject<MessageEvent> {
    if (!this.subject) {
      this.subject = this.create(url);
      console.log("Successfully connected: " + url);
    }
    return this.subject;
  }

  private create(url): ReplaySubject<MessageEvent> {

    //create connection
    let ws = new WebSocket(url);

    //define observable
    let observable = Observable.create(
      (obs: Observer<MessageEvent>) => {
        ws.onmessage = obs.next.bind(obs);
        ws.onerror = obs.error.bind(obs);
        ws.onclose = obs.complete.bind(obs);
        return ws.close.bind(ws);
      });

    //define observer
    let observer = {
      next: (data: Object) => {
        if (ws.readyState === WebSocket.OPEN) {
          console.log("---sending ws message---");
          ws.send(JSON.stringify(data));
        }
      }
    };

    return ReplaySubject.create(observer, observable);
  }
}

NotificationService

import { Injectable } from '@angular/core';
import { Observable, Subject, ReplaySubject, BehaviorSubject } from 'rxjs/Rx';
import { WebsocketService } from './websocket.service';
import { Notification } from './../model/notification'

const NOTIFICATION_URL = 'ws://localhost:8080/Kwetter/socket'


@Injectable()
export class NotificationService {

  public _notification: ReplaySubject<Notification>;

  constructor(websocketService: WebsocketService) {

    this._notification = <ReplaySubject<Notification>>websocketService
      .connect(NOTIFICATION_URL)
      .map((response: MessageEvent): Notification => {
        let data = JSON.parse(response.data);
        return {
          sender: data.author,
          message: data.message
        }
      });
  }

  sendMessage(notification) {
    console.log("---calling .next()---");
    this._notification.next(notification);
  }
}

NotificationComponent

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

@Component({
  selector: 'app-notifications',
  templateUrl: './notifications.component.html',
  styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent implements OnInit {

  notification: Notification;
  text: string;

  constructor(private notificationService: NotificationService, private userService: UserService) {

    if (this.notification == null) {
      this.notification = new Notification("", "");
    }
    notificationService._notification.subscribe(notification => {
      console.log("---notification has been updated---")
      this.notification = notification;
    });
  }

  sendMsg() {
    let newNot = new Notification(this.userService.getUser(), this.text);
    this.notificationService.sendMessage(newNot);
  }

  ngOnInit() {
  }

}

HeaderComponent

    import { Component, OnInit, OnDestroy } from '@angular/core';
import { UserService } from '../../services/user.service';
import { NotificationService } from '../../services/notification.service';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { Profile } from '../../model/profile';
import { User } from '../../model/user';
import { Notification } from '../../model/notification';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit, OnDestroy {

  private notification: Notification;
  private loggedIn = false;
  private user: User;

  private subscription: Subscription;

  constructor(private userService: UserService, private router: Router, private notificationService: NotificationService) {

    console.log("---constructor headercomponent---");
    console.log(this.notification);

    this.notificationService._notification.subscribe(notification => {
      console.log("---header notification has been updated---");
      this.notification = notification;
    });

    if (this.notification == null) {
      this.notification = new Notification("", "");
    }

    this.subscription = this.userService.profile$.subscribe(user => {
      this.user = user;
      if (user !== null) {
        this.loggedIn = true;
      }
      else this.loggedIn = false;
    });

    this.loggedIn = userService.isLoggedIn();
    this.user = userService.getUser();
  }

  logout() {
    this.userService.logout();
    this.router.navigate(['home']);
  }

  home() {
    this.router.navigate(['home']);
  }

  myProfile() {
    console.log("click");
    this.router.navigate(['profile', this.userService.getUser().id]);
  }

  getLoggedIn(): void {
    this.loggedIn = !!this.userService.isLoggedIn();
  }

  ngOnInit() {
    this.getLoggedIn();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

使用router-outlet显示NotificationComponent,并且始终使用选择器标记显示标题组件,但我认为这不重要。

<div>
  <app-header></app-header>
  <div class="content">
    <router-outlet></router-outlet>
  </div>
</div>

我找到了下面的帖子,建议使用ReplaySubject,以防我在事件被触发后订阅(我不认为是这种情况,但我还是尝试过)。这没用。

另外,我只有一个app.module,我声明了提供者。 由于我对两个组件使用相同的代码,为什么.subscribe仅在NotificationComponent中工作?

Angular 2: Observable / Subscription not triggering

Console view

1 个答案:

答案 0 :(得分:1)

您看到的行为与RxJS的工作方式以及流的创建方式有关。我们来看看WebsocketService

let observable = Observable.create(
  (obs: Observer<MessageEvent>) => {
    ws.onmessage = obs.next.bind(obs);

obs对于每个订阅都是新的,但ws始终是相同的。因此,当您在NotificationComponent中第二次订阅时,onmessage回调仅针对该订阅调用next。因此,只有该组件接收消息。

您可以在notificationService._notification.subscribe中注释掉NotificationComponent来验证这一点。然后HeaderComponent将收到消息。

一个简单的解决方案是在share中添加NotificationService运算符:

this._notification = <ReplaySubject<Notification>>websocketService
  .connect(NOTIFICATION_URL)
  .map((response: MessageEvent): Notification => {
    let data = JSON.parse(response.data);
    return {
      sender: data.author,
      message: data.message
    }
  })
.share();

这意味着.share()上游的订阅将被共享,即(obs: Observer<MessageEvent>) => { ws.onmessage = obs.next.bind(obs);将仅被调用一次,并且两个组件都将接收消息。

Btw。:RxJs提供support for websockets。您可以使用Observable.webSocket(url);创建一个流,并删除一些代码。