我有一个从 api 和依赖于该解决方案的服务获取数据的解决方案。取决于解析的服务将向多个组件提供数据部分,并且预计仅在页面加载时运行一次。这是相关的代码(省略了导入和一些注释):
产品详细信息.service.ts
@Injectable()
export class ProductDetailsService {
private productDetails: ProductDetails;
constructor(route: ActivatedRoute) {
this.productDetails = route.snapshot.data['product'];
}
public getProductDetails(): ProductDetails {
return this.productDetails;
}
}
Run Code Online (Sandbox Code Playgroud)
产品详细信息.resolve.ts
@Injectable()
export class ProductDetailsResolve implements Resolve<ProductDetails> {
constructor(private httpService: HttpService) { }
resolve(route: ActivatedRouteSnapshot): Observable<ProductDetails> {
return this.httpService.getProductDetails(route.params['id']);
}
}
Run Code Online (Sandbox Code Playgroud)
app-routing.module.ts
const routes: Routes = [
{ path: 'main/:id', component: MainComponent, resolve: { product: ProductDetailsService } },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)
some.component.ts
export class …Run Code Online (Sandbox Code Playgroud)