代码之家  ›  专栏  ›  技术社区  ›  Ajay Kulkarni

Angular 19-重新路由到子路由未按预期工作

  •  1
  • Ajay Kulkarni  · 技术社区  · 7 月前

    我有两个组成部分: claims-summary claims-insights 当我在 索赔摘要 组件,URL将是“/reclaims summary/claimId/”。当我从以下位置导航时 索赔摘要 索赔见解 ,新的URL应该是“/reclaims summary/claimId/reclaims insights/type”。所以我添加了一个子路由器。

    app.routes.ts:

    import { Routes } from '@angular/router';
    import { LoginComponent } from './components/login/login.component';
    import { HomeComponent } from './components/home/home.component';
    import { ClaimsSummaryComponent } from './components/claims-summary/claims-summary.component';
    import { ClaimsInsightsComponent } from './components/claims-insights/claims-insights.component';
    import { ClaimsComponent } from './components/claims/claims.component';
    
    export const routes: Routes = [
        { path: '', component: LoginComponent }, // Default route for login
        { path: 'home', component: HomeComponent }, // route for home
        { path: 'claims', component: ClaimsComponent }, // route for claims
        {
            path: 'claims-summary/:claimID',
            component: ClaimsSummaryComponent,
            children: [
                {
                    path: 'claims-insights/:type',  
                    component: ClaimsInsightsComponent,
                },
            ],
        },
        // { path: 'claims-summary/:claimID', component: ClaimsSummaryComponent }, // route for claims summary
        // { path: 'claims-insights/:type', component: ClaimsInsightsComponent },
        { path: '**', redirectTo: '', pathMatch: 'full' }, // Redirect any unmatched route to error page (Reminder to ask Akanksha to design error page)
    ];
    

    索赔摘要组成部分:

    // for claim ID from previous page
    claimId: string | null = null;
    
    constructor(private activatedRoute: ActivatedRoute) {}  
    redirectTo(type: string) {
        const claimID = this.activatedRoute.snapshot.paramMap.get('claimID');
        if (claimID) {
          this.router.navigate(['claims-insights', type], { relativeTo: this.activatedRoute });
        } else {
          console.error("reroute is failing"); 
        }
    }  
    

    claims-insights.compontent.ts:

    import { Component } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    import { CommonModule } from '@angular/common';
    import axios from 'axios';
    import { MatExpansionModule } from '@angular/material/expansion';
    import { MatTableModule } from '@angular/material/table';
    import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
    import { MatCardModule } from '@angular/material/card';
    import { environment } from '../../../environments/environment';
    import { HeaderComponent } from "../../views/header/header.component";
    import { FooterComponent } from '../../views/footer/footer.component';
    import { GenAssistComponent } from '../../views/gen-assist/gen-assist.component';
    import { MatChipsModule } from '@angular/material/chips'; 
    import { MatIconModule } from '@angular/material/icon';
    import { MatListModule } from '@angular/material/list'
    
    interface SummaryData {
      [key: string]: {
        details: string;
        lastUpdated: string;
      };
    }
    
    @Component({
      selector: 'app-claims-insights',
      imports: [
        CommonModule,
        MatExpansionModule,
        MatTableModule,
        MatProgressSpinnerModule,
        MatCardModule,
        HeaderComponent,
        FooterComponent,
        GenAssistComponent,
        MatChipsModule,
        MatIconModule,
        MatListModule
    ],
      templateUrl: './claims-insights.component.html',
      styleUrl: './claims-insights.component.scss'
    })
    export class ClaimsInsightsComponent {
    
      data: any = null; // Holds the fetched data
      type: string = ''; // Holds the type (medical or financial)
      isLoading: boolean = true; // To show a loading spinner or message
      queryType: string='';
    
      constructor(private activatedRoute: ActivatedRoute) {}
    
      async ngOnInit(): Promise<void> {
        // Get the type parameter from the route
        this.type = this.activatedRoute.snapshot.paramMap.get('type') || '';
        
        // Determine the query_type based on the type parameter
        switch (this.type) {
          case 'financial':
            this.queryType = 'detailed_financial';
            break;
          case 'litigation':
           this.queryType = 'detailed_litigation';
            break;
          case 'medical':
           this.queryType = 'detailed_medical';
            break;
          default:
            console.error('Invalid type parameter.');
            this.isLoading = false;
            return;
        }
    
        // Construct the API URL
        const claimId = 'claimId'; // Replace with dynamic claimId if needed... My plan is to put a function here
        const url = `${environment.apiBaseUrl}?query_type=${this.queryType}&claim_id=${claimId}`;
    
        // Fetch the data
        try {
          const response = await axios.get(url);
          console.log('API Response:', response.data); // Debug: Log API response
          this.data = response.data; // Store API response
        } catch (error) {
          console.error(`Error fetching ${this.type} data:`, error);
          this.data = `Error fetching ${this.type} data.`;
        } finally {
          this.isLoading = false; // Hide the loading spinner
        }
      }
    
      goBack() {
        window.history.back();
      }
    
    }  
    

    当我打电话的时候 redirectTo(type: string) {} 函数中,URL从“/reclaims summary/claimId/”更改为“/reclaim summary/claimId/reclaims insights/type”,但不会重定向到 索赔见解 组件。我错过了什么?

    1 回复  |  直到 7 月前
        1
  •  1
  •   Yong Shun    7 月前

    As ClaimsInsightsComponent 是下面的嵌套路由 ClaimsSummaryComponent ,它只能在添加时显示 <router-outlet> 元素在视图中 索赔摘要部分 .

    索赔摘要.组件.html

    <router-outlet></router-outlet>
    

    请注意,这将显示两者 索赔摘要部分 ClaimsInsightsComponents 当您浏览“/claimsummary/{claimId}/claimsinsights/{type}”时,在同一视图中。

    Demo (Nested route) @ StackBlitz


    如果你只想显示 索赔观点组件 浏览上述URL时,您必须 压平 URL,而不是嵌套路由。

    export const routes: Routes = [
      ...
      {
        path: 'claims-summary/:claimID',
        component: ClaimsSummaryComponent,
      },
      {
        path: 'claims-summary/:claimID/claims-insights/:type',
        component: ClaimsInsightsComponent,
      },
      ...
    ];
    

    Demo (Flatten route) @ StackBlitz