在Angular中,订阅主题的组件应该能够接收到事件。如果组件没有收到事件,可能有以下几种原因:
import { Component, OnInit } from '@angular/core';
import { MyService } from 'path/to/my-service';
@Component({
selector: 'app-my-component',
template: '...',
})
export class MyComponent implements OnInit {
constructor(private myService: MyService) {}
ngOnInit() {
this.myService.mySubject.subscribe((data) => {
// 处理接收到的事件
});
}
}
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class MyService {
mySubject = new Subject();
sendData(data: any) {
this.mySubject.next(data);
}
}
import { Component, OnDestroy } from '@angular/core';
import { MyService } from 'path/to/my-service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-my-component',
template: '...',
})
export class MyComponent implements OnDestroy {
private subscription: Subscription;
constructor(private myService: MyService) {
this.subscription = this.myService.mySubject.subscribe((data) => {
// 处理接收到的事件
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
通过检查以上几个方面,应该能够解决订阅主题的组件不接收事件的问题。