【问题标题】:BehaviorSubject isn't being 'nexted'BehaviorSubject 没有被“下一个”
【发布时间】:2021-01-14 09:51:20
【问题描述】:

由于我不知道的原因,我无法“下一步”处理 BehaviorSubject。我不知道自己做错了什么,我正在通过视频教程一步一步地做,几乎得到了该教程中的所有内容,但它仍然不适合我。

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);
    }));
  }
}

当我切换到不同的路线时,BehaviorSubject 没有被“下一个”,它保持为空。这就是为什么当我尝试显示房间的“标题”时,我收到一个错误,即找不到 null 的属性“标题”。求救,我要拔头发了~!提前致谢。 /欧内斯特

【问题讨论】:

    标签: angular typescript firebase angularfire rxjs-observables


    【解决方案1】:

    我搜索了删除问题的选项,但没有成功。无论如何,我发现了我的错误:在应用程序路由中我有: {path: ': rootID"[...]} 而不是 {path':roomID'[...]}。冒号和 'roomID' 之间的空格破坏了一切。无论如何感谢任何看过的人 ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 2021-04-01
      • 2018-07-07
      相关资源
      最近更新 更多