diff --git a/packages/abc/reuse-tab/reuse-tab.service.spec.ts b/packages/abc/reuse-tab/reuse-tab.service.spec.ts index 7489d97a7..3e47bb110 100644 --- a/packages/abc/reuse-tab/reuse-tab.service.spec.ts +++ b/packages/abc/reuse-tab/reuse-tab.service.spec.ts @@ -1,4 +1,4 @@ -import { TestBed } from '@angular/core/testing'; +import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ActivatedRoute, Router, RouteReuseStrategy } from '@angular/router'; import { filter } from 'rxjs/operators'; @@ -513,7 +513,7 @@ describe('abc: reuse-tab(service)', () => { snapshot.routeConfig.loadChildren = {}; expect(srv.retrieve(getSnapshot(2))).toBeNull(); }); - it(`should be run _onReuseInit event hook`, () => { + it(`should be run _onReuseInit event hook`, fakeAsync(() => { const handle = { componentRef: { instance: { @@ -524,8 +524,10 @@ describe('abc: reuse-tab(service)', () => { const snapshot = getSnapshot(3); // handle srv.store(snapshot, handle); - srv.shouldAttach(snapshot); + // mock activate router + srv.store(snapshot, null); + tick(101); expect(handle.componentRef.instance._onReuseInit).toHaveBeenCalled(); - }); + })); }); }); diff --git a/packages/abc/reuse-tab/reuse-tab.service.ts b/packages/abc/reuse-tab/reuse-tab.service.ts index ce1e041ea..f223fc9c0 100644 --- a/packages/abc/reuse-tab/reuse-tab.service.ts +++ b/packages/abc/reuse-tab/reuse-tab.service.ts @@ -8,7 +8,7 @@ import { Router, ROUTER_CONFIGURATION } from '@angular/router'; -import { BehaviorSubject, Observable, Unsubscribable } from 'rxjs'; +import { BehaviorSubject, Observable, timer, Unsubscribable } from 'rxjs'; import { Menu, MenuService } from '@delon/theme'; import { ScrollService } from '@delon/util/browser'; @@ -433,6 +433,12 @@ export class ReuseTabService implements OnDestroy { } this._cached.push(item); } else { + // Current handler is null when activate routes + // For better reliability, we need to wait for the component to be attached before call _onReuseInit + const cahcedComponentRef = this._cached[idx]._handle?.componentRef; + if (_handle == null && cahcedComponentRef != null) { + timer(100).subscribe(() => this.runHook('_onReuseInit', cahcedComponentRef)); + } this._cached[idx] = item; } this.removeUrlBuffer = null; @@ -457,13 +463,7 @@ export class ReuseTabService implements OnDestroy { const data = this.get(url); const ret = !!(data && data._handle); this.di('#shouldAttach', ret, url); - if (ret) { - const compRef = data!._handle.componentRef; - if (compRef) { - this.componentRef = compRef; - this.runHook('_onReuseInit', compRef); - } - } else { + if (!ret) { this._cachedChange.next({ active: 'add', url, list: this._cached }); } return ret;