1

I have a parent chat-app component that renders two chat component, and i listen for changes in a service from the parent component using subcribe.

Not sure why but when I subscribe in the child component the subscribe work and get to the console.log() but when i try the same thing in the parent it doesn't get to the console.log()

child:


export class ChatComponent implements OnInit {
  @Input() userNumber = '';
  @Input() messageArray: { message: string, timeStamp: any, user: any }[] = [];

  userName = ''
  
  constructor(
    private formBuilder: FormBuilder,
    private instantChatservice: ChatService
  ) { }

  messageText = new FormControl('')

  chatForm = this.formBuilder.group({
    address: ''
  });

  ngOnInit() {
     this.instantChatservice.getItem()
     this.instantChatservice.watchStorage().subscribe((data: Array<any>) => {
       console.log('aaa from child');
      
       this.messageArray = data;
     })
  }

  onSubmit() {
    this.sendMessage()
    this.messageText.reset('')
  }

  sendMessage() {
    var messageObj = {
      message: this.messageText.value,
    }

    this.instantChatservice.sendMessage(messageObj);
  }
}

parent:

export class ChatAppComponent implements OnInit {
  messageArray: { message: string, timeStamp: any, user: any }[] = [];

  constructor(
    private instantChatservice: ChatService
  ) { }

  ngOnInit() {
    this.instantChatservice.getItem()
    this.instantChatservice.watchStorage().subscribe((data: Array<any>) => {
      this.messageArray = data;
      console.log('aaa from parent', this.messageArray);
    })
  }
}

service:

export class ChatService {

  sendMessage(data: any) {
    var messages = JSON.parse(this.getItem() || '{}');
    messages.push(data)
    this.setItem('messages', messages)
  }

  private storageSub = new Subject();

  watchStorage(): Observable<any> {
    return this.storageSub.asObservable();
  }

  setItem(key: string, data: any) {
    localStorage.setItem(key, JSON.stringify(data));
    this.storageSub.next(data);
  }

  getItem() {
    return localStorage.getItem('messages');
  }
}

Why the subscribe in the parent component don't get triggered?

shakedk
  • 71
  • 1
  • 6
  • Perhaps your chat service is not a singleton service, therefore its not shared between two components, parent and child component has its own instance of the service. – R4L_R4o Dec 23 '22 at 17:47

0 Answers0