繁体   English   中英

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

[英]Angular 5 Rxjs Subject.subscribe() not triggering in multiple components

我正在使用rxjs和subject更新我的两个组件。

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

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

我有一个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();
  }

}

通过使用路由器出口来显示NotificationComponent,并且总是通过选择器标签来显示标头组件,但是我认为这并不重要。

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

我发现以下线程,建议在事件触发后我订阅的情况下使用ReplaySubject(我不认为是这种情况,但无论如何我都尝试过)。 这没用。

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

角度2:可观察/订阅未触发

控制台视图

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

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

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

您可以通过在NotificationComponent注释掉notificationService._notification.subscribe来进行验证。 然后, HeaderComponent将接收消息。

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

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); 将仅被调用一次,并且两个组件都将接收消息。

顺便说一句:RxJs提供对websockets的支持 您可以使用Observable.webSocket(url);创建流Observable.webSocket(url); 并摆脱一些代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM