Me gustaría configurar mi componente Angular para que la página solo se cargue si la ID en la URL es válida. El punto aquí es que quiero proteger la página de los usuarios que ingresan manualmente una URL aleatoria y acceden a cualquier página.
Tengo un componente con listas. 
Si hago clic en "Mostrar detalles", Angular navega a la página de detalles. Me gustaría abrir esta página solo si la URL ingresada contiene una identificación válida. Para lograr esto, llamo a un servicio para recopilar todas las ID en una matriz de cadenas. Y luego examine si la ID ingresada es miembro de esa matriz.
Lo que he probado:
lista.componente.ts:
ngOnInit() { this.fetchLists(); } fetchLists() { from(this.listService.getGroups()) .pipe( takeUntil(this.destroy$) ) .subscribe({ next: (listUI: ListUI[]) => { this.listData = listUI; }, error: (error) => { this.logger.debug(error.message); this.certError = true; } }); }detalles.componente.ts:
ngOnInit() { this.fetchListsAndIDs(); if (this.validIDsList.includes(listID)) { this.router.navigateByUrl(`/groups/lists/${listID}/details`); } else {this.router.navigateByUrl(`/groups/lists`);} } fetchListsAndIDs() { from(this.listService.getGroups()) .pipe( takeUntil(this.destroy$) ) .subscribe({ next: (listUI: ListUI[]) => { const listData = listUI; this.validIDsList = listData.map((lists) => lists.id); }, error: (error) => { this.logger.debug(error.message); this.certError = true; } }); }app.routing.module.ts
{ path: 'groups/lists/${listID}/details', component: DetailsComponent }Se abre la página "grupos/listas/99999999999/detalles", sin datos, y "this.validIDsList" no está definido. ¿Puede alguien por favor ayudarme a solucionar esto?
Casi tienes el código correcto, pero te perdiste la parte de que this.fetchListsAndIDs() está ejecutando un observable asincrónico, por lo que tu bloque if..else se está ejecutando incluso antes de que se complete la llamada a la API.
Le sugiero que incluya la comprobación if...else dentro del controlador next() . He invertido las condiciones para verificar NO primero, ya que ya está en details.components.ts que representa la ruta ``/groups/lists/${listID}/detalles ) , solo debe redirigir al usuario de regreso a las lists si id no es válido, de lo contrario el componente debería continuar con su trabajo.
Agregué código para obtener el listId de la URL. Falta en el código que publicaste en la pregunta.
ngOnInit() { this.listID = this.route.snapshot.paramMap.get('listID'); this.fetchListsAndIDs(); } fetchListsAndIDs() { from(this.listService.getGroups()) .pipe( takeUntil(this.destroy$) ) .subscribe({ next: (listUI: ListUI[]) => { const listData = listUI; this.validIDsList = listData.map((lists) => lists.id); this.handleNavigation(); }, error: (error) => { this.logger.debug(error.message); this.certError = true; } }); } handleNavigation() { if (!this.validIDsList.includes(this.listID)) { this.router.navigateByUrl(`/groups/lists`); } else { // call the function to continue with details component } }