我有一个需要在NgOnInit
方法中设置和获取数据的 Angular 组件。
然而,由于时间的原因,数据的设置和数据的检索会有轻微的延迟。我想用NgZone
or解决这个问题,ChangeDetectionRef
但我不确定该怎么做。
我不想使用设定的间隔或时间延迟。
我在constructor
.
constructor(
readonly chromeStorageService: ChromeStorageService) {
this.chromeStorageService.loadData(this.chromeStorageKey);
}
在我的服务方法中,如果尚未在 Chrome 存储中设置数据,我会加载数据。
loadData(key: string) {
chrome.storage.local.get(
[key], async (result: {[key: string]: VersionStorage;}) => {
if (Object.keys(result).length === 0 &&
result.constructor ===
Object) { // check to see if object is there
const todaysDate = new Date().getTime();
const object = {timestamp: todaysDate, versionNumber: '3.0.9'};
chrome.storage.local.set({key: object});
}
});
}
然后我检索我的OnInit
方法的数据:
async ngOnInit() {
this.chromeStorageService.retrieveChromeStorageObject(
this.chromeStorageKey);
this.chromeStorageService.chromeStorageSubject
.pipe(takeUntil(this.ngDestroy), tap((chromeObject: VersionStorage) => {
this.shouldDisplay = this.isNewVersion(chromeObject);
}))
.subscribe();
}
但是延迟导致我的对象为空。有人能用NgZone
or帮助我解决这个问题ChangeDetectionRef
吗?