我有一个在组件中调用的服务,在尝试实现一些代码重用策略之前,该服务已经正常工作,但是现在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;
});
}
当直接调用service方法时,这很好用,但是现在我实现了serviceActions
对象,就是说cannot read property get of undefined
给什么?
答案 0 :(得分:0)
问题源于以下事实:对象上的打包函数从定义它的类中解引用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':{...}
};
保留对类中this
的引用。