【发布时间】:2019-09-07 01:02:32
【问题描述】:
我有一个在组件中调用的服务,在我尝试实施一些代码重用策略之前它正在工作,但现在 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
什么给了?
【问题讨论】:
-
这是不相关的注释,但您应该使用
HttpClient类,而不是Http;Http已被弃用一段时间。例如,您不需要使用HttpClient在地图中进行 json.parse -
在命名方法时遵循 TypeScript/JavaScript 约定也是一个好主意:强烈建议使用 camelCase 而不是 PascalCase 命名方法,就像在 dotnet 或 C 语言中所做的那样。
-
首先要说明几点, 1. 该应用程序是用 Angular 4.3 编写的,目前无法升级,最初是用
Http编写的,我需要在迁移之前考虑整个过程。 2. 我们主要是一家 C# 商店,所以 Pascal Case 是我们的首选。 -
也可以确认它是把它放在像这样的字典中导致问题的。
标签: angular typescript angular-services