【发布时间】:2022-07-27 01:44:52
【问题描述】:
我有一个包含 3 条路线的应用:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SearchComponent } from './pages/search/search.component';
import { CreateUserComponent } from './pages/create-user/create-user.component';
import { UserProfileComponent } from './pages/user/user-profile.component';
const routes: Routes = [
{
path: '',
redirectTo: 'search',
pathMatch: 'full'
},
{
path: 'search',
component: SearchComponent,
data: {
breadcrumb: 'Search'
}
},
{
path: 'create-user',
component: CreateUserComponent,
data: {
breadcrumb: 'Create User'
}
},
{
path: 'user/:auth0Id',
component: UserProfileComponent,
data: {
breadcrumb: 'Profile'
}
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class UserManagementRoutingModule { }
在 SearchComponent 模板中,我有一个按钮,点击时会发出 GET 请求:
search.component.html
<button nz-button nzType="primary" type="button"
(click)="searchAll()">{{ 'SEARCH.SEARCH-FORM.SEARCH-ALL-BTN' | translate }}</button>
search.component.ts
searchAll(): void {
this.tableLoadingText = 'SEARCH.RESULT.LOADING-SEARCH';
this.isTableLoading = true;
this.currentSearchType = 'searchAll';
this.scimB2bService.getAllUsers(this.pageSize, this.pageIndex).subscribe((res: IB2bScimUserList) => {
this.userList = res.Resources;
this.totalUser = res.totalResults;
this.mapUsers(this.userList);
this.triggerFeedback('success', 'SEARCH.STATUS.SUCCESS.SEARCH-ALL', null);
}, error => {
this.isTableLoading = false;
this.triggerFeedback('error', 'SEARCH.STATUS.ERROR.SEARCH-ALL', error);
});
}
在不丢失搜索结果的情况下转到“user/:auth0Id”路线并返回“搜索”路线的最简单方法是什么(我的意思是不必再次执行 GET 请求)?
谢谢!
【问题讨论】:
-
您应该在搜索组件上使用 ngOnDestroy,并在此生命周期挂钩中将所有最新数据存储在服务文件中的 BehaviourSubject 中,例如
this.searchService.searchData.next(YOUR_SEARCH_DATA)this。当搜索组件加载时,ngOnInit() 可以带回该数据。这是一种方法。如果您的数据很大,我更愿意这样做。如果没有,最好通过使用搜索字符串点击搜索 API 再次调用 GET 方法。