gpt4 book ai didi

javascript - 将 Angular 1 提供程序转换为 Angular 2 的正确方法是什么

转载 作者:行者123 更新时间:2023-11-30 00:03:23 27 4
gpt4 key购买 nike

有很多关于如何将 Angular 1 服务和工厂转换为 Angular2 的文档和示例,但我找不到任何关于如何将 ng1 提供程序转换为 ng2 中等效的东西的信息。

示例提供者

function AlertService () {
this.toast = false;

this.$get = getService;

this.showAsToast = function(isToast) {
this.toast = isToast;
};

getService.$inject = ['$timeout', '$sce'];

function getService ($timeout, $sce) {
var toast = this.toast,
alertId = 0, // unique id for each alert. Starts from 0.
alerts = []

return {
factory: factory,
add: addAlert
};

function factory(alertOptions) {
var alert = {
type: alertOptions.type,
msg: $sce.trustAsHtml(alertOptions.msg),
id: alertOptions.alertId,
toast: alertOptions.toast
};
alerts.push(alert);

return alert;
}

function addAlert(alertOptions) {
alertOptions.alertId = alertId++;
var alert = this.factory(alertOptions);

return alert;
}

}


}

angular
.module('angularApp', [])
.provider('AlertService', AlertService);

在 Angular 2 中,什么是正确的等价物?

最佳答案

好吧,感谢https://github.com/jhipster/generator-jhipster/issues/3664#issuecomment-251902173,我们终于弄明白了

这是 NG2 中的服务

import {Injectable, Sanitizer, SecurityContext} from '@angular/core';

@Injectable()
export class AlertService {

private alertId: number;
private alerts: any[];

constructor(private sanitizer: Sanitizer, private toast: boolean) {
this.alertId = 0; // unique id for each alert. Starts from 0.
this.alerts = [];
}

factory(alertOptions): any {
var alert = {
type: alertOptions.type,
msg: this.sanitizer.sanitize(SecurityContext.HTML, alertOptions.msg),
id: alertOptions.alertId,
toast: alertOptions.toast
};
this.alerts.push(alert);
return alert;
}

addAlert(alertOptions, extAlerts): any {
alertOptions.alertId = this.alertId++;
var alert = this.factory(alertOptions);
return alert;
}

isToast(): boolean {
return this.toast;
}
}

这是服务的提供者

import { Sanitizer } from '@angular/core';
import { AlertService } from './alert.service';

export function alertServiceProvider(toast?: boolean) {
// set below to true to make alerts look like toast
let isToast = toast ? toast : false;
return {
provide: AlertService,
useFactory: (sanitizer: Sanitizer) => new AlertService(sanitizer, isToast),
deps: [Sanitizer]
}
}

现在您需要在模块的提供程序声明中调用 alertServiceProvider 方法。

@NgModule({
imports: [
...
],
declarations: [
...
],
providers: [
...
alertServiceProvider()
],
exports: [
...
]
})
export class SharedCommonModule {}

该代码是 JHipster 项目的一部分,您可以浏览实际模板 here

关于javascript - 将 Angular 1 提供程序转换为 Angular 2 的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39418106/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com