Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services.

To address this problem, I modified my app navigation to use router-outlet and set up the 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)
},

In my parent module user-profile routing, I defined the following routes:

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

I intend to display user-seminar data whenever this link is clicked:

<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>

Despite trying various methods, my child component subscription doesn't work because I'm unable to retrieve employeeNumber data from the parent.

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

I'm struggling with passing the parent ngOnInit routes params data to the child component, user-seminar.

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

I attempted to use a service method that I came across in a Stack Overflow post. However, it didn't cover how to incorporate API usage.

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 query pertains to obtaining API data within services and then sharing it between my parent and child components. Would using this.http.get inside my service address this issue?

Answer №1

lectureTopics$ = new BehaviorSubject<any>();

this.lectureTopics.next(SOME_VALUE);

in lecture.component.ts:

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

in lecture.component.html:

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

If you need to preload data before rendering the component, you can do it in a guard and only allow the user to navigate after loading data for rendering

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: "btn" class vanishes when the button is toggled

I am facing an issue with the button's class change functionality. I am using the [ngClass] directive to switch between Bootstrap classes for the button style. However, when I click the button, the "btn" class seems to disappear from the code. Instead ...

Steer clear of using sourceMap files

Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "remove ...

There is only a singular font awesome icon that appears properly based on the conditions set by [ngClass

I'm currently developing a user profile feature that allows users to submit links to their social media accounts. Each account is represented by a clickable icon, and the selection of which icon to display is based on various conditions within [ngClas ...

Wait for the product details to be fetched before returning the products with a Firestore promise

Although I know similar questions have been asked numerous times before, I am struggling with something that seems quite straightforward to me. We have two tables - one called "order_lines" and the other called "order_lines_meta". My goal is to query the " ...

In Laravel, a post request can pass a class with a property that is of a different class type

In my Laravel controller, I have the following function: public function save(Request $request, ClientOrderDTO $clientOrderDTO){ } The definition of the ClientOrderDTO used above is as follows: use App\DTO\ClientDTO; class ClientOrderD ...

What is the best way to emphasize a row in an Angular Material table based on a

I am facing an issue with highlighting row colors conditionally in my code. Although there are no errors, the background color is not being applied to the rows as expected. I have a total of 5 rows with the 'riskIndex' value set to 'H'. ...

The formControl value is not being shown on the display

I am facing an issue with a form that has multiple fields created using formGroup and formControlName. The challenge arises when I launch the application and need to retrieve data from the back end to display it on the view. The specific problem I'm ...

Firebase V9: Uploading and Updating Documents

I am currently working on updating messages in Firebare for a chat functionality using the method below: markConversationAsSeen(conversationId: string, email: string) { const messages = collection(this.firestore, 'messages'); const q = q ...

What is the proper way to define a generic function that accepts a Union type as an argument?

I am dealing with various types and their unions. Here is the code snippet: type A = { name: string } type B = { work: boolean } type AB = A[] | B[] const func = (): AB => { return [{ name: 'ww' }] } const data = ...

The Mat-Datepicker will always show the current date in your local time zone, never in

Utilizing a datepicker and momentjs, I have successfully implemented sending UTC dates to my server. However, the issue arises when retrieving these UTC dates back into the date picker, as it always reflects my timezone (EST). This discrepancy can result i ...

Is it possible to configure TypeScript (or a tool similar to ESLint) to throw an error when a library returns undefined?

Currently working with knex and sometimes it returns any, for example when forgetting to specify the table type in the query. Are there any recommended tools available to avoid this issue, ensuring all knex queries are typed properly? ...

Utilizing svgr in NextJS with TypeScript and Webpack

I have a collection of separate svg files that I want to load in React and use as React components. Here is an example of how I am trying to do this: import SampleIcon from '@/components/editor/icons/add-column-after.svg'; <SampleIcon classNam ...

Issue with index creation using the @index decorator in Typegoose with NestJS and MongoDB

Encountering an issue with typegoose. Trying to create a 2dsphere index on the property geoLocation of model SP. Utilized the typegoose decorator @index but it's not functioning and not throwing any errors. Uncertain about how typegoose handles this s ...

Do we really need Renderer2 in Angular?

Angular utilizes the Renderer2 class to manipulate our view, acting as a protective shield between Angular and the DOM, making it possible for us to modify elements without directly interacting with the DOM ourselves. ElementRef provides another way to al ...

Replace a portion of text with a RxJS countdown timer

I am currently working on integrating a countdown timer using rxjs in my angular 12 project. Here is what I have in my typescript file: let timeLeft$ = interval(1000).pipe( map(x => this.calcTimeDiff(orderCutOffTime)), shareReplay(1) ); The calcTim ...

Adjust the size and color of text in Chart.js using Angular 5

Why does the font color in chartjs appear as light gray and not print when you want to do so from the page? I tried changing the font color of chartjs in the options attribute, but it didn't work. How can I change the font color in chartjs angular? ...

What is the reason behind requiring {[param: string]: string | string[]} for the HTTP GET attribute [params]?

Problem Statement An error occurs during type inference in this.http.get() Error TS2322: Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<IInfo[]>'. Type 'ArrayBuffer' is missing the followin ...

Verify whether any errors occurred in any controls within the specified form group

I have a group of controls and I would like any errors that occur to be immediately visible in the template. My .ts file: //... Some stuff export class FormularioFacturaComponent implements OnInit { // .... Some stuff private pcIVA = new Fo ...

The client PC running the Ionic app encountered an error while trying to load chunk 'XY'

I'm currently working with Ionic 3 and lazy loading. Everything is running smoothly on 12 different PCs. However, I encountered an issue on one PC where it started displaying the error message "Loading chunk 7 failed," sometimes with numbers like 43 o ...

What is preventing me from installing Angular Bootstrap?

Version Information: Angular CLI: 14.2.3 Node: 16.15.1 Package Manager: npm 8.12.1 Operating System: darwin x64 Encountered an error while trying to install Angular Bootstrap using NPM: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! ...