![](/img/trans.png)
[英]Can I load a Component one time for all child routes of a Module in Angular 6?
[英]Can i resolve services every time i load component and one time when i load module together without double request?
我有一個模塊 ,該模塊在加載時可解析服務 ,並且在該模塊中具有許多組件,但是我想在每次加載TrainingsComponent時都解析相同的服務 。 所以問題是,如果我打開TrainingsComponent ,它將是對服務的雙重查詢 。 為模塊下載服務很重要,因為組件中使用了此服務中的數據,而在TrainingsComponent中下載數據也很重要,因為我希望每次加載時都從服務中獲取新數據。 那我該怎么辦呢?
const routes: Routes = [
{
path: '',
resolve: {
setup: GamesListService, MissionsListService, TestService, EvolutionService
},
children: [
{
path: '',
component: TrainingsComponent,
resolve: {
setup: GamesListService, MissionsListService, TestService
},
},
{
path: 'mission-study',
component: MissionStudyComponent
},
{
path: 'sphere/:sphereAlias',
component: SingleSphereComponent
}
]
}
];
您應該考慮拆分服務。 為要加載到模塊上的數據創建單例服務,為每次加載請求時的數據創建另一個服務。 如果在那里有普通的東西,請將它們放在基本類中並進行擴展。
另一種解決方案是不從服務端發出請求。
將該代碼放入您的服務中:
export class ApiService {
private url = 'api/url';
constructor(private http: HttpClient) {}
load(): Observable<any> {
return this.http.get<any>(`${this.url}`); }
}
}
代替:
export class ApiService {
private url = 'api/url';
constructor(private http: HttpClient) {}
load(): Observable<any> {
return this.http.get<any>(`${this.url}`).pipe(...);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.