更改路线时不会触发我的观察物。
我的服务中有一个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;
})
}
}
但是从另一个组件(联接组件)重定向到该组件时,不会触发对此可观察对象的订阅。
答案 0 :(得分:2)
您的plunkr无法正常工作,但是我可以看到代码。您需要从providers: [ RoomsService ]
声明中删除AppComponent
。它导致RoomsService
的多个实例。另一种方法是也将其从NgModule.providers
中删除并添加:
@Injectable({
providedIn: 'root'
})
export class RoomsService {}
此外,您正在用this.rooms$
重新分配getRoom
中的return this.rooms$ = this.roomsCollection
属性。这可能不是您想要的