O. *_*per 25 javascript timeout angular
我必须在Angular 2环境中使用(大量)现有代码.该代码广泛使用AngularJS 1.x 中的$timeout服务.与代码中使用的各种其他AngularJS 1.x服务相反,我很难找到有关服务的Angular 2等效信息$timeout.
该角文档似乎并没有包含服务提及任何与timeout在其名称-something.文章从AngularJS升级确实提到了我面临的情景:
也许您想要访问AngularJS的内置服务,如
$location或$timeout.
遗憾的是,本文并未实际解释如何访问这些特定服务,因为后续示例HeroesService假定服务没有AngularJS 1.x提供的任何依赖项.
文章如这一个建议使用本机的setTimeout功能不辜负的功能$timeout服务,无论是.
如何$timeout在Angular 2环境中重现功能?
编辑:正如在答案中已经注意到的,setTimeout当使用Angular 2时,本机函数的缺点是无关紧要的.在这种情况下,如果我$q从AngularJS 1.x中获得了完整,我可以$timeout像这样大致复制函数:
function $timeout(fn, delay) {
var result = $q.defer();
setTimeout(function () {
$q.when(fn()).then(function (v) {
result.resolve(v);
});
}, delay);
return result.promise;
}
Run Code Online (Sandbox Code Playgroud)
Max*_*kyi 12
使用setTimeout本机功能.不再需要在Angular中使用特殊服务.这是由于区域的引入,特别是NgZone.
像这样的文章建议使用本机setTimeout函数也不辜负$ timeout服务的功能.
为什么让你这么说?$timeout服务的主要任务是在执行延迟函数后开始摘要.你可以从消息来源看到它:
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
function($rootScope, $browser, $q, $$q, $exceptionHandler) {
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn.apply(null, args));
} catch (e) {
...
if (!skipApply) $rootScope.$apply(); <-------------------- here
}, delay);
Run Code Online (Sandbox Code Playgroud)
在Angular中zone.js拦截所有异步操作并开始在Angular中更改检测,Angular是一种增强版本的摘要.
如果你需要复制$timeout,你可以大致这样做:
function $timeout(fn, delay, ...args) {
let timeoutId;
$timeout.cancel = $timeout.cancel || function (promise) {
if (promise && promise.$$timeoutId in $timeout.promises) {
$timeout.promises[promise.$$timeoutId][1]('canceled');
delete $timeout.promises[promise.$$timeoutId];
return clearTimeout(promise.$$timeoutId);
}
return false;
};
$timeout.promises = $timeout.promises || {};
const promise = new Promise((resolve, reject) => {
timeoutId = setTimeout(function () {
try {
resolve(fn.apply(null, args));
} catch (e) {
reject(e);
} finally {
delete $timeout.promises[promise.$$timeoutId];
}
}, delay);
$timeout.promises[timeoutId] = [resolve, reject];
});
promise.$$timeoutId = timeoutId;
return promise;
}
// some basic testing
$timeout((v) => {
console.log('a', v);
}, 2000, 7);
const promise = $timeout(() => {
console.log('b');
}, 3000);
promise.catch((reason) => {
console.log(reason);
});
$timeout.cancel(promise);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26183 次 |
| 最近记录: |