【问题标题】:BehaviorSubject between components on route change路由更改时组件之间的 BehaviorSubject
【发布时间】:2019-05-26 06:23:55
【问题描述】:

路由更改不会触发我的 observable。

我的服务中有一个 behaviorSubject。

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { Rooms } from '../../models/Rooms';
import { UsersService } from '../users/users.service';

@Injectable()
export class RoomsService {
    roomsModel: Rooms
    private _roomsSubject: BehaviorSubject<Rooms> 
    rooms$: Observable<Rooms>

    constructor(private usersService: UsersService ) {
        this._roomsSubject = new BehaviorSubject<Rooms>(this.roomsModel)
        this.rooms$        = this._roomsSubject.asObservable()
    }
}

当我在组件(等待组件)上订阅它时,订阅被触发并且我有了对象。

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { UsersService } from 'src/app/services/users/users.service';
import { RoomsService } from 'src/app/services/rooms/rooms.service';
import { Rooms } from 'src/app/models/Rooms';
import { Users } from 'src/app/models/Users';

@Component({
  selector: 'app-waiting',
  templateUrl: './waiting.component.html',
  styleUrls: ['./waiting.component.scss']
})
export class WaitingComponent implements OnInit {

  isHost: boolean
  room: Rooms
  users: Users[]

  constructor(private route: ActivatedRoute, private userService: UsersService, private roomsService: RoomsService) { }

  ngOnInit() {
    this.isHost = (this.route.snapshot.params['host'] == "true")?true:false

    if(this.isHost){
      this.roomsService.createRoom()
    }

    this.roomsService.rooms$.subscribe(room => {
      console.log(room) 
      this.room = room; 
    })    
  }


}

但是从另一个组件(join 组件)我被重定向到这个组件,订阅这个 observable 没有被触发。

我的来源在这里: https://plnkr.co/edit/q2x9z9vPe5ZFyKcb1XUo

【问题讨论】:

  • 嗯无法运行您的 plunkr 代码 :(

标签: angular rxjs observable


【解决方案1】:

您的 plunkr 无法正常工作,但我可以看到代码。您需要从 AppComponent 声明中删除 providers: [ RoomsService ]。它导致RoomsService 的多个实例。另一种方法是将其也从NgModule.providers 中删除并添加:

@Injectable({
    providedIn: 'root'
})
export class RoomsService {}

另外,您正在使用return this.rooms$ = this.roomsCollection 重新分配getRoom 中的this.rooms$ 属性。这可能不是你想要的

【讨论】:

  • 还是不行。在join组件上重定向之前,(this.room)的一个console.log返回'undefined',等待组件中的console log仍然没有触发
  • 您正在用return this.rooms$ = this.roomsCollection 重新分配getRoom 中的this.rooms$ 属性
  • 我太笨了……谢谢!
猜你喜欢
  • 2019-12-15
  • 1970-01-01
  • 2017-09-13
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 2018-01-05
  • 2017-07-04
相关资源
最近更新 更多