[英]Communicate between components through a service and a Subject
我有一个服务和两个组件。就像一个孩子的父母关系。
子组件有一个带有过滤器 function 的按钮。 然后结果将显示在父组件中。 我首先在没有服务的情况下拥有它,并且在子组件中使用了 EventEmitter。 但现在我已将 api 调用放在单独的服务中。 所以现在我想使用一个主题而不是 EventEmitter。 但问题是现在我不知道如何在父组件中显示结果。
是时候展示一些代码了。 所以这是服务:
export class ExtendedSearchService {
private _filterparticipantByRegistration$ = new Subject<ParticipantInfoDTO[]>();
data = this._filterparticipantByRegistration$.asObservable();
filerByRegistration(selectedValue: any, startDate: Date): Observable<ParticipantInfoDTO[]> {
return this.participantService
.filterParticipantsByRegistration(1, selectedValue as any, moment(startDate).format('YYYY MM D'))
.pipe();
}
}
和子组件:
这是子组件上的按钮
<button
[disabled]="!buttonFilterDisabled || !selectedValue || !selectedValueOptie || !startDate || !selectedQrcode"
mat-raised-button
color="accent"
class="Button"
(click)="searchFor()"
>
Filter
</button>
在这里,我在子组件中使用该服务:
searchFor() {
if (this.selectedSearch === 'Registratie') {
this.extendedSearchService
.filerByRegistration(this.selectedValue, this.startDate)
.subscribe(filterByRegistration => {
this.filterparticipant.emit(filterByRegistration);
});
}
}
这一切都有效。
但现在父组件:
所以在这个组件中,结果必须显示在网格中:
<app-extended-search [@searchOpen]
(clickCloseSearch)="handleClickCloseSearch()"
[searchExtended]="searchExpanded"
(filterparticipant) = "applyExtendedFilter($event)"
class="extended-search"
[ngClass]="{expanded: searchExpanded}"
></app-extended-search>
所以我会解释一下。 我关于这条线:
(filterparticipant) = "applyExtendedFilter($event)"
所以这是过去使用 EventEmitter。 但现在我在服务中使用了一个主题。 那么如何替换这个呢?
这是父组件的js代码:
applyExtendedFilter(filteredParticipants: ParticipantInfoDTO[]) {
this.datasource.data = filteredParticipants;
}
我必须在这件功能上进行哪些更改?
所以在父模板中我有这样的:
<app-extended-search [@searchOpen]
(clickCloseSearch)="handleClickCloseSearch()"
[searchExtended]="searchExpanded"
[_filterparticipantByRegistration] = "_filterparticipantByRegistration$.asObservable()"
class="extended-search"
[ngClass]="{expanded: searchExpanded}"
></app-extended-search>
然后我会得到这个错误:
无法绑定到“_filterparticipantByRegistration”,因为它不是“app-extended-search”的已知属性。
在父组件中,我有这样的:
applyExtendedFilter(filteredParticipants: ParticipantInfoDTO[]) {
this.datasource.data = filteredParticipants;
this.extendedSearchFilterService.filerByRegistration(this.selectedValue, this.startDate);
}
基本上,这就是Subject
的工作方式。
父组件.html
<app-child [childSubject]="childSubject.asObservable()"></app-child>
父组件.ts
@Output() childSubject: Subject<boolean> = new Subject<boolean>(true);
clickEvent(){
this.childSubject.next(true);
}
Child.Component.html
<div></div>
子组件.ts
@Input() childSubject: Subject<boolean> = new Subject<boolean>();
this.childSubject.subscribe(res => {
Console.log(res);
});
_filterparticipantByRegistration$ 在您的服务中是私有的。 因此,您会收到此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.