问题描述
由于我未知的原因,我无法“下一步” BehaviorSubject。我不知道我在做什么错,我正在通过视频教程逐步进行操作,获得了该教程中几乎所有的内容,但仍然对我不起作用。
聊天窗口.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);
}));
}
}
当我在其他路线上切换时,BehaviorSubject不会被“继续”显示,而是保持为空。这就是为什么当我尝试显示房间的“标题”时,我遇到一个错误,即找不到null的属性“ title”。我求救,我正在拔头发〜!提前致谢。 /欧内斯特
解决方法
我搜索了一个删除问题的选项,但没有成功。无论如何,我发现了自己的错误:在应用路由中,我遇到了: {path:':rootID“ [...]}而不是{path':roomID'[...]}。冒号和'roomID'之间的空格破坏了所有内容。无论如何,感谢任何看过这个东西的人;)