我有以下代码。我正在寻找Angular 5中的承诺模块和$ q,但没有找到任何有用的详细信息。下面的代码在AngularJS和Javascript中。
我想将此代码传输到Angular 5和TypeScript。 这是一个模拟数据的模拟服务:
angular.module('reports.appActivity').factory('AppActiveMockServices', ['$q',
function ($q) {
var appActivity;
function loadappActivity(params) {
var deferred = $q.defer(),
cancel = function (reason) {
deferred.resolve(reason);
};
injectappActivity(params);
deferred.resolve(appActivity);
return {
promise: deferred.promise,
cancel: cancel
};
}
function injectappActivity(params) {
var total = Math.floor((Math.random() * 100)),
someUsage = total - Math.floor((Math.random() * 80)),
tempValue,
maxIndex = 0,
deltaTime=0,
daysSelected,
timeBegin,
timeEnd,
d = new Date(),
dayInmilliseconds;
appActivity = {total: total, items: []};
deltaTime = 24 * 3600 * 1000; // daily
timeBegin = (params.timestamp_start).getTime();
timeEnd =(params.timestamp_end).getTime();
daysSelected = Math.round((timeEnd - timeBegin) / 3600/24/1000);
if (daysSelected <= 1 ) {
maxIndex = 24 ; // one day , resolution is hourly data
deltaTime = 3600 * 1000; // hourly
dayInmilliseconds = (d.getTime() - (24 * 3600 * 1000));
}
else if (daysSelected <= 7) {
maxIndex = 7; // 7 days , resolution is daily data
dayInmilliseconds = (d.getTime() - (7* 24 * 3600 * 1000));
}
else if (daysSelected <= 30) {
maxIndex = 30; // 30 days , resolution is daily data
dayInmilliseconds = (d.getTime() - (30* 24 * 3600 * 1000));
}
else { // custom range
maxIndex = daysSelected; // x days , resolution is daily data
dayInmilliseconds = (d.getTime() - (daysSelected * 24 * 3600 * 1000));
}
for (var index = 0; index < maxIndex; index++) {
d.setTime(dayInmilliseconds + (index * deltaTime));
total = Math.floor((Math.random() * 100));
tempValue = Math.floor((Math.random() * 50));
someUsage = (tempValue > total) ? total : (total - tempValue);
var item = {
'total': total,
'some_usage': someUsage,
'date': d.toISOString().slice(0, 19) + 'Z'
};
appActivity.items.push(item);
}
}
return {
loadappActivity: loadappActivity
};
}
]);
非常感谢任何帮助。
答案 0 :(得分:0)
在Angular 5中查找...承诺和$ q,但找不到有用的详细信息
在Angular中,假设你单独留下polyfills.ts,你应该能够像我下面的例子一样使用Promise
想要...将此代码转移到使用Angular 5和Typescript。
这是让你前进的基本设置,我不打算复制所有代码,因为我看到一些缺失/奇怪的东西可能对修复有更大的影响(例如你有一个参数从未使用的arg,以及从未定义过的函数injectappActivity
考虑使用angular cli来生成服务
ng generate service app-active-mock
然后像这样更新
# app-active-mock.service.ts
@Injectable()
export class AppActiveMockService {
public loadappActivity(): Promise<any> {
return Promise.resolve(...)
}
}
也有点无关,但你很可能没有想到任何有用的搜索与Angular中的Promise相关的东西,因为在大多数情况下,社区已经接受了Observables