Angular 服务参数未定义

Angular Service Parameter undefined

我有一个在组件中调用的服务,在我尝试实施一些代码重用策略之前它一直在工作,但现在 http 客户端没有按定义进入。该组件像这样调用适当的函数:

//actions object that maps the request on the object
//split between the different areas of the app.
serviceActions: {[name: string]: {[name: string]:(...args: any[]) => Observable<any>}} = {
    'Customer':{
        GetCategories: this._service.GetCategories,
    }
    'Admin':{...}
};
// source string referenced in the function call
source: string = 'Customer';

//the actual call being made
this.serviceActions[this.Source].GetCategories(...).subscribe(...)

此代码正在调用以 http 作为参数的服务上的函数:

//service constructor:
 constructor(private httpClient: Http) { }
//service method:
public GetCategories(showAll = false, parentId = 0): Observable<Array<SelectModel>> {
        let link = AppSettings.API_COMMON_CATEGORIES;
        let params: URLSearchParams = new URLSearchParams();
        params.set('showAll', showAll.toString());
        params.set('parentId', parentId != null ? parentId.toString() : null);
        let requestOptions = new RequestOptions();
        requestOptions.search = params;

        return this.httpClient.get(link, requestOptions).map(response => {
            let result = JSON.parse(response.json());
            let list = new Array<SelectModel>();
            let caregories: Array<any> = result;

            caregories.forEach(category => {
                list.push(this.CreateSelectModel(category));
            });

            return list;
        });
    }

当直接调用服务方法时,这工作正常,但现在我已经实现了 serviceActions 对象,它说 cannot read property get of undefined

什么给了?

问题源于对象上的打包函数从定义它的 class 中取消引用 this。为了解决这个问题,我们应该将函数包包装在另一个传递参数的匿名函数中。

所以代替:

serviceActions: {[name: string]: {[name: string]:(...args: any[]) => Observable<any>}} = {
    'Customer':{
        GetCategories: this._service.GetCategories,
    }
    'Admin':{...}
};

确实应该是:

serviceActions: {[name: string]: {[name: string]:(...args: any[]) => Observable<any>}} = {
    'Customer':{
        GetCategories: (params) => this._service.GetCategories(params),
    }
    'Admin':{...}
};

在 class 中保留对 this 的引用。