首页 > 解决方案 > 带有@NGRX/Data 的自定义端点

问题描述

我需要使用@NGRX/Data 修改我的端点。我编写了一个在文档中描述的数据服务,它确实改变了端点,问题是数据没有加载到存储中。如何使用此自定义数据服务并在收到数据后将数据加载到存储中?

@Injectable()
export class OfficeCustomService extends DefaultDataService<Office> {
    userId: number;
    territoryId: number;

    constructor(http: HttpClient ) {
        const url = new DefaultHttpUrlGenerator(new DefaultPluralizer([appPluralNames]));
        url.registerHttpResourceUrls({Label: {entityResourceUrl: 'office', collectionResourceUrl: 'offices'}});
        super('Office', http, url, defaultDataServiceConfig);
    }

    protected execute(method: HttpMethods, url: string, data?: any, options?: any): Observable<any> {
        const regex = /offices/gi;
        if (method === 'GET' && url.search(regex) > 0) {
            url = url + 'userId/' + this.userId + '/territoryId/' + this.territoryId;
        }
        return super.execute(method, url, data, options);
    }

    getAllByUserAndTerritory(userId: number, territoryId: number): Observable<Office[]> {
        this.userId = userId;
        this.territoryId = territoryId;
        return super.getAll();
    }

}

为什么 super.getAll() 函数不将数据加载到存储中?

标签: angular-ngrx-data

解决方案


我无法弄清楚为什么 super.getAll() 不起作用,但我找到了解决方法。我没有将用户 ID 和区域 ID 传递给自定义函数,而是将它们从数据服务的存储中拉出来。不是我想做的,但它确实有效。

@Injectable()
export class OfficeCustomService extends DefaultDataService<Office> {
    userData: User;

    constructor(
        http: HttpClient,
        store: Store ) {
        const url = new DefaultHttpUrlGenerator(new DefaultPluralizer([appPluralNames]));
        url.registerHttpResourceUrls({Label: {entityResourceUrl: 'office', collectionResourceUrl: 'offices'}});
        super('Office', http, url, defaultDataServiceConfig);
        store.select(fromState.getUser).subscribe((user: User) => {
            this.userData = user;
        });
    }

    protected execute(method: HttpMethods, url: string, data?: any, options?: any): Observable<any> {
        const regex = /offices/gi;
        if (method === 'GET' && url.search(regex) > 0) {
            url = url + 'userId/' + this.userData.id + '/territoryId/' + this.userData.territoryId;
        }
        return super.execute(method, url, data, options);
    }
}

推荐阅读