Angular 应用程序中的事件发射器通知后成功发送网络请求时出现问题

Problems Sending Network Request Successfully after Event Emitter Notification in Angular App

在我的 Angular 应用程序中,我向 return 一些基于用户选择的过滤器的过滤数据发出网络请求。这按预期工作。接收过滤器值并发出请求的函数如下所示:

public onFilterReceived(values)
{
    let languageFilter = [];
    let cityFilter = [];
    let zipFilter = [];
    let firstNameFilter = [];
    let lastNameFilter = [];

    this.route.params.subscribe(
        (params: any) => {
            this.page = params['page'];
            this.pn_zip_e = params['pn_zip.e'];
            this.pn_firstName_e = params['pn_firstName.e'];
            this.pn_lastName_e = params['pn_lastName.e'];
            this.pn_city_e = params['pn_city.e'];
            this.pn_language_e = params['pn_language.e'];
        }
    );

    this.pn_language_e === "1" ? languageFilter = values['language'] : languageFilter = [];
    this.pn_city_e === "1" ? cityFilter = values['city'] : cityFilter = [];
    this.pn_zip_e === "1" ? zipFilter = values['zip'] : zipFilter = [];
    this.pn_firstName_e === "1" ? firstNameFilter = values['firstName'] : firstNameFilter = [];
    this.pn_lastName_e === "1" ? lastNameFilter = values['lastName'] : lastNameFilter = [];

    this.sendDebouncedRequest(this.page, this.pagesize, languageFilter, cityFilter, zipFilter, firstNameFilter, lastNameFilter);
};

现在,在应用程序上,我们还有一些 UI 让用户更改分支,这将随后过滤整个应用程序中的所有数据。因为分支更改 UI 在不同的组件中,所以我使用事件发射器通过共享服务向其他组件宣布此更改。

我的目标是接收此事件的通知,然后再次触发网络请求。后端将从那里处理数据过滤。

我 运行 遇到的问题是,在通过事件发射器成功接收到事件通知并将引用传递给要触发的函数后,在接收组件中看起来像这样:

this.branchChangeSub = this.branchInfoService.selectedBranchChange.subscribe(this.onBranchChange);

...当我通过此代码再次触发网络请求功能时:

public onBranchChange(values) {
    console.log('announceBranchChange firing...');
    if (values) {
        console.log('have values...');
        this.onFilterReceived(values); // Resend the network request
    }
}

...我收到此错误:

TypeError: Cannot read property 'onFilterReceived' of undefined

这就是我感到困惑的地方。为什么 onFilterReceived() 这里未定义?为什么我在组件加载时可以成功触发此功能,但在我收到分支更改通知后却不能。我在这里有一些根本性的误解。

尝试更新 subscribe 中对 onBranchChange() 的调用,以使用箭头函数来保留 this 的上下文:

this.branchChangeSub = this.branchInfoService.selectedBranchChange.subscribe(values => this.onBranchChange(values));

希望对您有所帮助!