【问题标题】:Callback function as dependency in angular 2回调函数作为角度 2 中的依赖项
【发布时间】:2018-03-28 08:34:38
【问题描述】:

我正在编写一个扩展类的 Angular 服务。在我的服务的构造函数中,我调用了超级构造函数。超级构造函数需要一个回调函数。我不能这样做。回调因为 super 必须是 在派生类的构造函数中访问 this 之前调用。所以我将回调作为参数传递给构造函数。这种方法的问题是我的服务的用户不需要传递回调函数。请建议我在这里调用回调函数的方法。 我需要这个回调,因为 parentService 返回给我的结果是我需要在我的代码中进一步使用的回调。

      @Injectable()
            export class MyService extends someClass{

            constructor(@Inject(MY_CONFIG) private config: MyConfig, callback :(results: string, errorDesc: string) => void ) {
            //can't do this.callback
                super(config.id, config.name, callback);
            }
            callback(results: string, errorDesc: string)
            {
             //do something here with the results
            }
    }

//Non angular (Pure typescript class)

    export class someClass
{

    private _resultReceivedCallback: resultReceivedCallback = null;

    constructor(id: any , name : any ,  resultReceivedCallback: resultReceivedCallback)
    {
        this._resultReceivedCallback = resultReceivedCallback;

        if (this._resultReceivedCallback) {
            //process results here
            this._resultReceivedCallback.call( results, errorDesc);
        }

    }
}

【问题讨论】:

  • 为什么不覆盖任何调用的实现并以这种方式链接您的功能,而不是尝试通过构造函数传递它。
  • @Igor - 我没听懂你。你能提供一个代码sn-p吗?
  • 如果您需要更多帮助,我认为您最好提供minimal reproducible example,因为我可能不明白这个问题。
  • @Igor - 我已经用更多细节更新了这个问题。
  • 该问题没有包含有关如何使用 MyService 以及 callback 应来自何处的示例。回调函数不应该用作依赖项。上面的代码没有解释为什么一个类应该从另一个类继承。 en.wikipedia.org/wiki/Composition_over_inheritance 很有可能在这里适用。

标签: angular typescript


【解决方案1】:

据我所见,我建议使用 Promises/Observers。更专业,解决你想达到的。

如果你需要例子,写我会分享

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2012-03-06
    相关资源
    最近更新 更多