For reasons unknown to me I'm not able to 'next' the BehaviorSubject. I don't know what I'm doing wrong, I'm doing it step by step with video tutorial, got almost everything like in that tutorial and it's still not working for me.
chat-window.component.ts
import { Component, OnDestroy, OnInit, } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
import { ChatroomsService } from '../../services/chatrooms.service';
@Component({
selector: 'app-chat-window',
template: `
<div class="row">
<div class="col-sm-12">
<app-room-title [room]="room"></app-room-title>
<app-message></app-message>
<app-input></app-input>
</div>
</div>
`,
styleUrls: ['./chat-window.component.css']
})
export class ChatWindowComponent implements OnInit, OnDestroy {
subscriptions: Subscription[] = [];
room: any;
constructor(private chatroomsService: ChatroomsService, private acivatedRoute: ActivatedRoute) {
this.subscriptions.push(
this.chatroomsService.roomTaken.subscribe(chatroom => {
this.room = chatroom;
}));
}
ngOnInit(): void {
this.subscriptions.push(
this.acivatedRoute.paramMap.subscribe(parameters => {
const chatroomId = parameters.get('roomID');
this.chatroomsService.changeTheRoom.next(chatroomId);
})
);
}
ngOnDestroy() {
this.subscriptions.forEach(subscription => {subscription.unsubscribe(); });
}
}
room-title.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-room-title',
template: `<p>{{room.title}}</p>`,
styleUrls: ['./room-title.component.css']
})
export class RoomTitleComponent {
@Input() room: any;
constructor(){}
}
chatrooms.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { AngularFirestore } from '@angular/fire/firestore';
import { switchMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ChatroomsService {
public changeTheRoom: BehaviorSubject<string | null> = new BehaviorSubject(null);
public roomTaken: Observable<any>;
constructor(private angularFirestore: AngularFirestore) {
this.roomTaken = this.changeTheRoom.pipe(switchMap(roomID => {
if (roomID) {
return angularFirestore.doc(`chatRooms/${roomID}`).valueChanges();
}
return of(null);
}));
}
}
When I'm switching on a different route, the BehaviorSubject isn't being 'nexted', it remains null. That's why, when I try to display 'title' of room, I'm getting an error, that can't find property 'title' of null. I beg for help, I'm pulling my hair out~! Thanks in advance. /Ernest
I searched for an option to delete a question but didn't succeed. Anyway, I found my mistake: in app-routing I had: {path: ': rootID"[...]} instead of {path':roomID'[...]}. The space between the colon and 'roomID' destroyed everything. Thanks anyway for anyone who took a look ;)