steps for invoking a different component method

I am struggling to figure out how to render the workload component's learningHours method after the setStatusOfUser() method in confirmation.ts. Can someone please help me with this issue?

Here is my confirmation.ts component:

import { Component, Inject, OnInit } from '@angular/core';
import { MatDialog, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { courses } from '../models/courses';
import { CoursesService } from '../services/course.service';

@Component({
  selector: 'app-confirmation',
  templateUrl: './confirmation.component.html',
  styleUrls: ['./confirmation.component.css']
})
export class ConfirmationComponent implements OnInit {
  msg: string = '';
  condition:boolean;
  courseList: Array<courses>;

  constructor(private courseService: CoursesService,  @Inject(MAT_DIALOG_DATA) public data: any,
  public dialog: MatDialog,) { }

  ngOnInit(): void {
   
  }
  getAllCourses(){
    this.courseService.getAllCourses('PATKRISH').subscribe((data) => {
      this.courseList = data;
      console.log(this.courseList);
    });
  }
  setStatusOfUser(){
    this.courseService.setStatus(this.data.courseId,'PATKRISH').subscribe((data)=>{
      this.msg=data;
      this.getAllCourses()
     
    })
    this.condition=true;
    this.courseService.getAllCourses('PATKRISH').subscribe((data) => {
      this.courseList = data;
      console.log(this.courseList);
    });
  
  }

}

My goal is to render the workload component's learningHours method after the setStatusOfUser() method.

Here is the workload.component.ts:

 import { Component, OnInit } from '@angular/core';
import { WorkloadService } from '../services/workload.service';



@Component({
  selector: 'app-workload',
  templateUrl: './workload.component.html',
  styleUrls: ['./workload.component.css']
})
export class WorkloadComponent implements OnInit {

  constructor(private workloadService:WorkloadService) { }

  workload:number=0;

  ngOnInit(): void {
    this.learningHours()
  }
  learningHours (){
    this.workloadService.getWorkloadPercentage("PATKRISH").subscribe(
      data => {
        if(data==0){
         this.workload=0;
        }else{
          this.workload=data;
        }
        console.log(data);
      },
      error=>{console.log(error);
      this.workload=0;}
    );
  }

}

course.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
import { courses } from '../models/courses';

// import { AddProgress } from '../interface/progress';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    
  }),
};
@Injectable({
  providedIn: 'root',
})
export class CoursesService {
  private subject = new Subject<any>();
  constructor(private httpClient: HttpClient) {}
  // http://localhost:8080/api/addassignment/coursebyuserid/PERAVIKA
  getAllCourses(userId: any): Observable<courses[]> {
    return this.httpClient.get<courses[]>(
      `http://localhost:8080/api/addassignment/coursebyuserid/${userId}`
    );
  }
  setStatus(courseId: any, userId: any): Observable<string> {
    return this.httpClient.put<string>(
      `http://localhost:8080/api/addassignment/${courseId}/${userId}`,
      httpOptions
    );
  }
}

workload.sevice.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class WorkloadService {
  constructor(private _http: HttpClient) {}

  getWorkloadPercentage(id: string): Observable<number> {
    return this._http.get<number>(
      `http://localhost:8080/api/learningmeter/getmeter/PATKRISH`
    );
  }
}

Answer №1

Instead of manually calling ngOnInit, let the framework handle it as a lifecycle method that is triggered when the component is initialized.

To execute the functionality currently in the ngOnInit method at a different time, consider moving it to a separate method not tied to component initialization.

If you need this functionality both during initialization and later on, simply invoke the new method from within ngOnInit.

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

The function "overloading" of the union type is not functioning properly

I attempted to "overload" a function by defining it as a union function type in order to have the type of the input parameter dictate the type of the `data` property in the returned object. However, this resulted in an error: type FN1 = (a: string) => { ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Angular 4's async pipe triggers an endless loop when used in conjunction with a method call

How can I create a select UI element with dynamic options using a method that returns an observable based on the inputs provided? TypeScript (Component class) retrieveCars(type : string, engine : string) : Observable<Cars>{ return this.carServi ...

Tips for effectively handling the response of a post request in Angular 5

Hi there, I've hit a roadblock with a login situation. It's supposed to send this data using a post method: POST URL: /user/login?_format=json Header: Content-Type: application/json POST data: { "name": "username", "pass": "password" } ...

What is the best way to iterate through an enum?

The type 'string' cannot be assigned to the type 'online' or 'offline'. I must be overlooking something, but I'm not sure what it is. enum StatusOptions { ONLINE = 'ONLINE', OFFLINE = 'OFFLINE', ...

Facing a continuous issue where the Angular Universal Bundle keeps loading but only displays a

As I attempted to convert a basic Angular application into a universally supported application, I made all the necessary changes such as adding checks on DOM elements like window, navigator, setTimeout, etc. After running the command npm run build:ssr &am ...

Customizing CSS for tables within a mat-menu in Angular Material

I am currently developing an application using Angular 7 and Angular Material cdk 6. This is my first experience working with Angular Material and I am facing a challenge in overriding the CSS styles of my columns. Despite several attempts, none of them se ...

Unable to retrieve any data from BehaviorSubject within the observable

Trying to pass data inside an observable function from multiple services to an unrelated component without using service calls by utilizing BehaviorSubject has yielded mixed results. service.ts export class Data{ name:string; age:number; class:string; ...

Issue with Angular 2's event emitter malfunctioning

I have a dashboard component and a bottom-nav component. When the setting icon in the bottom-nav component is clicked, I want an alert to appear in the parent dashboard component. Here is the code: dashboard.component.ts ===== html part ====== <div cl ...

Separate your HTML code and move it to a different HTML document within Angular CLI

Is there a way to extract my HTML section from the file app.compontent.ts and place it in a separate HTML document? I've tried adding the HTML code directly into the generated class app.component.ts but it doesn't seem to work. I'd also lik ...

Instructions for redirecting to "http://localhost:4200/shops/shop1/dashboard" following a successful authentication through Auth0 in an Angular

Post-login, Auth0 redirects only to the root URL at http://localhost:4200 instead of http://localhost:4200/shops/shop1/dashboard. The official documentation from Auth0 states: After successful authentication, callbacks will only be made to specific URLs. ...

What is the most effective method for identifying duplicate values in a multidimensional array using typescript or javascript?

I have a 2D array as shown below: array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ] I am looking to compare the values in the array indexes to check for duplicates. For example array[0] = [1,1]; array[1] = [1,2]; array[2] = [1,1]; We can see that ...

The error message "Property 'name' does not exist on type 'User'" is encountered

When running this code, I expected my form to display in the browser. However, I encountered an error: Error: src/app/addproducts/addproducts.component.html:18:48 - error TS2339: Property 'price' does not exist on type 'ADDPRODUCTSComponent& ...

What is the process for switching views by tapping on a button?

Currently, I am working on a registration form that consists of 3 steps. I need to change the view of the form to another view when clicking the Next button. I have been attempting to achieve this in Angular 2 by using routing, but it seems to be replacin ...

Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts rega ...

Please refresh the page to view the updated component

Within my Angular 7 application, I have various components that retrieve data from an API by making a call in the ngOnInit function. So far, the CRUD operations are functioning correctly and I am able to obtain the desired results. However, the main issue ...

The validation through class-validator or class-transformer fails to function properly when applying multiple Types to the @Query decorator

Is there a way to combine multiple types with the @Query() decorator in my controller, such as ParamsWithRegex and PaginationParams? I'm facing an issue where no validation is being applied when I do that. How can I resolve this problem? **// MY CON ...

Angular 8 directive for concealing phone numbers

I am currently facing an issue with my phone mask directive that is designed to accept US format phone numbers. The problem arises when I try to clear the input by deleting one character at a time using the backspace key, as the value in the input field do ...

Guide on utilizing a module in TypeScript with array syntax

import http from "http"; import https from "https"; const protocol = (options.port === 443 ? "https" : "http"); const req = [protocol].request(options, (res) => { console.log(res.statusCode); }); error TS2339 ...