calling subscribe in the parent component doesn't work, but does work in child component rxjs angular

347 Views Asked by At

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?

1

There are 1 best solutions below

0
EyeOfPhoenix On

the subject is old, but just in case,

checks if 'import' is the same in 'parent' and 'child' if both are not in the same module, e.g. Intellij sets the relative path to the component and not to the module alone.