未來的任何其他方法
一個可能的解決方案可能是您的服務如下@RunOutsideAngular
裝飾:
declare let Zone: any;
export function RunOutsideAngular(target: any) {
Object.getOwnPropertyNames(target.prototype)
.filter(p => typeof target.prototype[p] === 'function')
.forEach(p => {
let originalMethod = target.prototype[p];
target.prototype[p] = function (...args) {
let self = this;
Zone.root.run(() => originalMethod.apply(self, args));
}
});
let ctor: any = function (...args) {
let self = this;
return Zone.root.run(() => target.apply(self, args));
};
ctor.prototype = target.prototype;
return ctor;
}
Plunker Example
如果你只想setTimeout
和setInterval
一些類中的禁用就可以修補這些功能
function patchTimers(timers: any[]) {
timers.forEach((timer) => {
let originalMethod = window[timer];
window[timer] = function (...args) {
let self = this;
if (Zone.current['__runOutsideAngular__'] === true && Zone.current.name === 'angular') {
Zone.root.run(() => originalMethod.apply(self, args));
} else {
originalMethod.apply(this, arguments);
}
};
})
}
patchTimers(['setTimeout', 'setInterval']);
,創造裝飾這樣
export function RunOutsideAngular(target: any) {
Object.getOwnPropertyNames(target.prototype)
.filter(p => typeof target.prototype[p] === 'function')
.forEach(p => {
let originalMethod = target.prototype[p];
target.prototype[p] = function (...args) {
Zone.current['__runOutsideAngular__'] = true;
originalMethod.apply(this, args);
delete Zone.current['__runOutsideAngular__'];
}
});
let ctor: any = function (...args) {
Zone.current['__runOutsideAngular__'] = true;
let instance = target.apply(this, args);
delete Zone.current['__runOutsideAngular__'];
return instance;
};
ctor.prototype = target.prototype;
return ctor;
}
然後你就可以按如下方式使用它
@RunOutsideAngular
export class Service {
constructor() {
setInterval(() => {
console.log('ctor tick');
}, 1000);
}
run() {
setTimeout(() => {
console.log('tick');
}, 1000);
setInterval(() => {
console.log('tick interval');
}, 1000)
}
}
Plunker Example
你檢查:https://stackoverflow.com/questions/43108155/angular-2-how-to-keep-event-from-triggering-digest-loop? ' – echonax
'錯誤:沒有提供ChangeDetectorRef!'。似乎ChangeDetectorRef的提供者不可用於服務。 –
你爲什麼要在服務中運行變更檢測?它沒有看法。 – echonax