【问题标题】:Angular Service Parameter undefined角度服务参数未定义
【发布时间】: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 类,而不是HttpHttp 已被弃用一段时间。例如,您不需要使用 HttpClient 在地图中进行 json.parse
  • 在命名方法时遵循 TypeScript/JavaScript 约定也是一个好主意:强烈建议使用 camelCase 而不是 PascalCase 命名方法,就像在 dotnet 或 C 语言中所做的那样。
  • 首先要说明几点, 1. 该应用程序是用 Angular 4.3 编写的,目前无法升级,最初是用Http 编写的,我需要在迁移之前考虑整个过程。 2. 我们主要是一家 C# 商店,所以 Pascal Case 是我们的首选。
  • 也可以确认它是把它放在像这样的字典中导致问题的。

标签: angular typescript angular-services


【解决方案1】:

问题源于对象上的打包函数从定义它的类中取消引用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 的引用。

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 2018-03-21
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多