如何在Angular中构建懒惰加载侧边栏



我在我的Angular应用程序中构建了一个处理客户端信息的组件;这是我的ClientDetailsComponent,在这个组件中有其他子组件,当用户进入主ClientDetailsComponent时,每个子组件都会获取自己的数据;这当然会导致主组件加载很多用户目前可能不需要的东西,所以我试图寻找一种方法来延迟加载这些部分。

现在,我的组件有一个侧边栏,作为导航菜单,只在单击时显示特定的部分,现在我已经构建了一个非常原始的导航菜单,依靠类来隐藏/显示每个部分。

ClientDetailsCompent

<div class="wrapper">
<div class="sidebar-nav">
<nav>
<ul class="sections-list" btnRadioGroup [formControl]="navControl">
<li btnRadio="0" tabindex="0" role="button">Basic Information</li>
<li btnRadio="1" tabindex="0" role="button" *ngIf="!isNew">PPC Accounts</li>
<li btnRadio="2" tabindex="0" role="button" *ngIf="!isNew">Campaign Groups</li>
<li btnRadio="4" tabindex="0" role="button" *ngIf="!isNew">Optimizations</li>
<li btnRadio="5" tabindex="0" role="button" *ngIf="!isNew">Branding</li>
<li btnRadio="3" tabindex="0" role="button" *ngIf="!isNew">Sharing</li>
</ul>
</nav>
</div>
<div class="content">
<div class="wsm-container">
<!-- Basic Information -->
<section id="basic-info" class="wsm-card mx-auto d-none" [ngClass]="navControl.value === '0' ? 'd-flex' : 'd-none'">
</section>
<!-- PPC Accounts -->
<section *ngIf="!isNew" id="ppc-accounts" class="wsm-card mt-4 d-none" [ngClass]="navControl.value === '1' ? 'd-flex' : 'd-none'">
</section>
<!-- Campaign Groups -->
<section *ngIf="!isNew && navControl.value === '2'" class="wsm-card mt-4 d-none" [ngClass]="navControl.value === '2' ? 'd-flex' : 'd-none'">
<app-campaign-groups [clientID]="param"></app-campaign-groups>
</section>
<!-- Optimizer History -->
<section *ngIf="!isNew && navControl.value === '4'" id="optHistory" class="wsm-card mt-4 d-none" [ngClass]="navControl.value === '4' ? 'd-flex' : 'd-none'">
<app-optimization-history></app-optimization-history>
</section>
<!-- Branding -->
<section id="brnading" class="wsm-card mx-auto d-none" [ngClass]="navControl.value === '5' ? 'd-flex' : 'd-none'">
</section>
</div>
</div>
</div>

关于导航,一切都和我预期的一样,一次只显示一个部分,这取决于我在侧边栏上点击了哪个项目;然而,这样做并不能阻止在访问组件时同时发出所有请求。

因此,在尝试各种选项时,我发现了一个解决方法,即在该节的*ngIf指令上使用navControl.value === ''条件,因此,我不仅使用[ngClass]指令更改类,而且还阻止将该节添加到DOM中,事实上,我看到只有在单击所需选项卡时才会对每个子组件发出请求。

现在的问题是,每次我点击不同的选项卡时都会发出请求,因为每次我在各个部分之间移动时都会添加/删除组件。

有没有一种方法可以在我访问子组件后保持加载状态,这样它就不需要重新渲染并再次获取数据

使用ReplaySubject:创建服务

@Injectable({
providedIn: "root"
})
export class DataService {
private _replay: ReplaySubject<any>;
get replay() {
if (!this._replay) {
this._replay = new ReplaySubject();
this.fakeFetch().then(data => this.replay.next(data));
}
return this._replay;
}
async fakeFetch() {
console.log("fakeFetch");
await new Promise(c => setTimeout(() => c(), 10));
return { name: "world" };
}
}

在您的组件中订阅重播主题:

export class HelloComponent {
name: string;
constructor(private api: DataService) {
console.log('render HelloComponent')
this.api.replay.subscribe(data => {
this.name = data.name;
});
}
}

堆叠式

最新更新