【发布时间】:2020-10-30 00:45:00
【问题描述】:
我在服务中公开了两个主题,因此我可以呈现主题中的值并将它们呈现在我的页面上。
其中一个主题正确接收了信息,但第二个主题自动关闭订阅,我无法再检索数据。
这是我的代码:
// service.ts
clientSubject: Subject<any>;
jobSubject: Subject<any>;
constructor(private clientService: ClientService, private jobService: JobService) {
this.clientSubject = new Subject();
this.jobSubject = new Subject();
}
fetchData(): void {
this.clientService.getClients()
.pipe(
map(clients => clients.map(
client => this.jobService.getJobs(client.clientId)
.pipe(
map(jobs => jobs.map(job => ({client, job})))
)
.subscribe(this.jobSubject)
)
))
.subscribe(this.clientSubject);
}
这是我的组件中的代码:
clients: any;
jobs: any;
constructor(private invoiceService: InvoiceService) {}
ngOnInit(): void {
this.invoiceService.clientSubject.subscribe(d => {
this.clients = d;
console.log(this.clients);
});
this.invoiceService.jobSubject.subscribe(d => {
this.jobs = d;
console.log(this.jobs);
});
this.invoiceService.fetchData();
}
这是控制台记录的内容:
### this.jobs data ###
invoices.component.ts:25
[{…}]
0: {client: {…}, job: {…}}
length: 1
__proto__: Array(0)
### this.clients data ###
invoices.component.ts:19
(2) [SubjectSubscriber, SubjectSubscriber]
0: SubjectSubscriber {closed: true, _parentOrParents: null, _subscriptions: null, syncErrorValue: null, syncErrorThrown: false, …}
1: SubjectSubscriber {closed: true, _parentOrParents: null, _subscriptions: null, syncErrorValue: null, syncErrorThrown: false, …}
length: 2
__proto__: Array(0)
为什么主题订阅者会根据fetchData 中的实现覆盖this.clients 数据?
jobService.getJobs(client.clientId) 返回一个 observable,格式如下:
[{jobId: 1, name: 'blabla', items: []}]
jobService.getClients() 返回一个 observable,格式如下:
[{clientId: 1, name: 'blabla', isParent: false}]
【问题讨论】: