我肯定在这里错过了一些东西;我有一个看起来像这样的Angular组件:
@Component({
selector: 'lobby',
templateUrl: './lobby.component.html',
styleUrls: ['./lobby.component.scss'],
providers: [LobbyService, LobbyUsersService, LobbyActivityService]
})
它在组件中提供了3个服务,根据文档,它们与该组件一起被销毁。
在其中一项服务中,我有一个可观察的订阅:
@Injectable()
export class LobbyUsersService {
constructor(private _http: HttpClient, private _socketioService: SocketioService) {this._url = environment.url;
}
subscribe() {
this._socketioService.socketIoConnectObs.subscribe((connect: boolean) => {
if (connect) {
....
....
}
});
}
此事件的发布者通过以下方式在单例服务中声明:
@Injectable({
providedIn: 'root'
})
export class SocketioService {
private _socketIoConnectSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
public socketIoConnectObs: Observable<boolean> = this._socketIoConnectSubject.pipe(filter(val => val !== null));
....
....
this._socket.on('connect', () => {
this._socketIoConnectSubject.next(true);
});
}
我的问题是,为什么即使在“大厅”组件被销毁并且我当前被路由到另一个组件之后,服务LobbyUsersService的订阅仍被调用?
答案 0 :(得分:3)
您需要在LobbyUsersService
中管理订阅,并在服务被销毁时取消订阅。您可以通过让LobbyUsersService
实现OnDestroy
来做到这一点。
import { Injectable, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Injectable()
export class LobbyUsersService implements OnDestroy {
private _socketIOSubscription: Subscription;
constructor(
private _http: HttpClient,
private _socketioService: SocketioService
) {
this._url = environment.url;
}
subscribe() {
this._socketIOSubscription = this._socketioService.socketIoConnectObs
.subscribe((connect: boolean) => {
if (connect) {
....
....
}
});
}
ngOnDestroy() {
if (this._socketIOSubscription) {
this._socketIOSubscription.unsubscribe();
}
}
}