angulartypescriptangular11router-outlet

How to get api data in router outlet - Angular


My problem is i cannot pass parent data ngOnInit route params to my child component user-seminar. So i tried google searching and arrive a solution through services.

I have changed my app navigation to router-outlet and i have main app-routing.

{
        path: 'users/:employee_number',
        canActivate: [AuthGuard],
        data: {permission: 'view_user'},
        loadChildren: () => import('./features/user-profile/user-profile.module').then(m => m.UserProfileModule)
},

Here is my parent module user-profile routing

const routes: Routes = [
    { path: '', component: UserProfileComponent, 
        children: [
            {
                path: 'information',
                component: UserInformationComponent
            },
            {
                path: 'seminar',
                component: UserSeminarComponent
            },
        ]
    },
];

Here i want to display user-seminar data whenever this link is click

<a [routerLink]="['seminar']" data-toggle="collapse" aria-expanded="false"
    class="nav-link">
    <i class="nav-icon fas fa-user"></i>
    <p class="nav-text">
        Seminar/Workshops Attended
    </p>
</a>

Here is my child component subscribe that doesn't work because i can't get my employeeNumber data from parent.

private getUserSeminar(): void {
    console.log(this.employeeNumber);
    this.apiService.getSeminar('users/seminar/', this.employeeNumber)
    .subscribe(
        data => {
          this.seminar = data;
        });
  }

Here is my parent ngOnInit routes params that i can't i pass this data to user-seminar child

ngOnInit() {
        this.routes.paramMap.subscribe(paramMap => {
            this.employeeNumber = Number(paramMap.get('employee_number'));
        });
        
}

Tried using services method that i found in one of stackoverflow post. But doesn't talk about using api.

seminarSet:any;
    seminarSets: Subject<any> = new Subject<any>();

    constructor(private http: HttpClient) {
        this.seminarSets.subscribe((value) => {
            this.seminarSet = value;
        });
    }

    seminarData(seminarSet: any) {
        this.seminarSets.next(seminarSet);
}

My question is how can i get the api data in services then share it to my parent and child components. Do i use this.http.get inside my service?


Solution

  • seminarSets$ = new BehaviorSubject<any>();
    
    this.seminarSet.next(SOME_VALUE);
    

    in *.component.ts:

    this.someSharedService.seminarSets$.subscribe(seminarSets => {/**/})
    

    in *component.html:

    <div *ngIf="(someSharedService.serseminarSets$ | async) as seminarSets">
    <!-- here u can use seminarSets variable -->
    </div>
    

    if u need preload data before render comonent - u can do it in guard and allow user to navigate only after load data for render