Quentin Albert
Quentin Albert

Reputation: 590

Confusing behavior of a BehaviorSubject in my Angular App

I recently ran into a problem and can't really figure out what's wrong with my code at this point, hopefully someone of you can help me.

All I am trying to do is changing the value of my BehaviorSubject with a function but it isn't working out.

chat.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class ChatService {
  chatId = new BehaviorSubject<number>(0);

  constructor() {
    this.chatId.next(1);
  }

  changeChatId(chatId: number) {
    console.log(chatId);
    this.chatId.next(chatId);
  }
}

So the subscribers get the default as well as the changed chatId from the constructor. But as soon as I try to change it with the changeChatId function nothing happens at all. The right id's get passed into the function I already debugged that but the line this.chatId.next(chatId) doesn't seem to do anything.

ADD

These are the other components the service is currently used in.

chat-message-list

import { Component, OnInit, Input} from '@angular/core';
import { ChatService } from "../../../shared/services/chat.service";

@Component({
  selector: 'app-chat-message-list',
  templateUrl: './chat-message-list.component.html',
  styleUrls: ['./chat-message-list.component.css'],
  providers: [ChatService]
})
export class ChatMessageListComponent implements OnInit {
  chatId: number;

  constructor(private chat: ChatService) { }

  ngOnInit() {
    this.chat.chatId.subscribe(
      chatId => this.updateMessageList(chatId)
    );
  }

}

chat-item

import { Component, OnInit, Input} from '@angular/core';
import { User } from '../../../shared/models/user.model';
import { ChatService } from '../../../shared/services/chat.service';

@Component({
  selector: 'app-chat-list-item',
  templateUrl: './chat-list-item.component.html',
  styleUrls: ['./chat-list-item.component.css'],
  providers: [ChatService]
})
export class ChatListItemComponent implements OnInit {
  @Input() 
  user: User;

  constructor(private chat: ChatService) { }

  ngOnInit() {
  }

  onChatItemSelected(){
    this.chat.changeChatId(this.user.id);
  }
}

Upvotes: 1

Views: 82

Answers (1)

LLai
LLai

Reputation: 13396

You need to make your ChatService a singleton (shared) service. Add it to the providers of your ngModule. This allows all the components that use the ChatService to share the same service instance.

@NgModule({
    providers: [ChatService]
})

And remove it from your components providers. When you are adding it to your components providers, that component gets its own instance of ChatService which can not be used by other components.

Upvotes: 1

Related Questions