Invoking the asynchronous function Subscription within the ngOnInit lifecycle hook of a component

retrieving data from my service without waiting for it to complete.

This is the Component responsible for fetching data for my grid. The issue lies in this part: this.store.loadRequestHistory(this.id). When hovering over store, no data is displayed from items.

export class HistoryGridComponent implements OnInit {

  id: number;

 constructor(private route: ActivatedRoute, 
             private router: Router, 
             public store: HistoryStore) {
  }


  ngOnInit() {
      this.route.paramMap
          .map((params: ParamMap) => params.get('id'))
          .subscribe(id => {
              this.id = parseInt(id, 10);
              let list =  this.store.loadRequestHistory(this.id); // Data needed here 
          });
  }

Below is the method from a service/store that successfully retrieves the data.

@action public async loadRequestHistory(requestId: number): Subscription {
        this.loading = true;
        let history = new HistoryClient(this.http, environment.apiUrl);
        let response = history.getRequestHistory(requestId);
        return response.subscribe(
            (data) => {
                try {
                    this.items = _(data)
                        .map(historySummaryMapper.map)
                        .value();

                    this.itemCount = data.length;

                    this.loading = false;
                }
                catch (error) {
                    console.log(error);
                    this.loading = false;
                }


            },
            (error) => {
                console.log(error);
                this.loading = false;
            },
            () => {
                 this.loading = false;
            }
        );
    }

Answer №1

Give this a shot - use async/await along with returning observable.

 ngOnInit() {
      this.route.paramMap
          .map((params: ParamMap) => params.get('id'))
          .subscribe(async id => {
              this.id = parseInt(id, 10);

        let requestData=  await this.store.loadRequestHistory(this.id).toPromise();// Fetching data here 

          });
  }


 public loadRequestHistory(requestId: number): Observable<any> {
        this.loading = true;
        let historyData = new HistoryClient(this.http, environment.apiUrl);
        let response = historyData.getRequestHistory(requestId);
        return response;
   }

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 call with Ajax failed due to an error: TypeError - this.X is not a function

I am encountering an issue when trying to invoke the successLogin() function from within an Ajax code block using Typescript in an Ionic v3 project. The error message "this.successLogin() is not a function" keeps popping up. Can anyone provide guidance on ...

The flatMap function is not operating as intended in the sequence of function calls

Having difficulty organizing a chain of calls using TypeScript with RxJS observables I am new to RXJS and I am struggling to structure a chain of calls in my TypeScript code. My question is - how can I ensure that this.http.get(''); is only cal ...

Struggling to containerize an Angular application

Struggling to deploy my Angular application as a docker image on Azure, I have hit a roadblock. Following the steps outlined in a video tutorial at https://learn.microsoft.com/en-us/azure/developer/javascript/tutorial-vscode-docker-node-01?tabs=bash did no ...

What is the best way to generate an object in TypeScript with a variety of fields as well as specific fields and methods?

In JavaScript, I can achieve this using the following code: var obj = { get(k) { return this[k] || ''; }, set(k, v) { this[k] = v; return this; } }; obj.set('a', 'A'); obj.get('a'); // returns &ap ...

Ways to identify modifications from a BehaviorSubject and automatically trigger a response according to the updated value

I am currently implementing a BehaviorSubject for managing languages in my Angular project. I am also utilizing Angular Datatables and trying to dynamically change the language displayed in the data table based on the value returned from the subscription. ...

Resetting the modal scroll time when the content of the modal is refreshed

I have implemented the modal in my application using ng-bootstrap. Within the modal, there are multiple pages that can be navigated using the Next and Back buttons. An issue I am facing is that when a page is long and requires scrolling, it loads in the ...

Implementing Generic Redux Actions in Typescript with Iterable Types

Resolved: I made a mistake by trying to deconstruct an object in Object.assign instead of just passing the object. Thanks to the assistance from @Eldar and @Akxe, I was able to see my error in the comments. Issue: I'm facing a problem with creating a ...

Tips for invoking a function from a JavaScript file within an Angular component

This particular query remains unanswered and pertains to AngularJS. I am seeking a solution specifically for Angular, as none of the existing answers online seem to be effective in my case. Here is an outline of my code: Columns.js export class Columns { ...

Angular 4: Loading components sequentially

I am currently working with Ionic 3 and based on the Angular 4 framework. I have a question regarding loading multiple children components asynchronously, one by one: Load parent component; Load first child component; After the first child component is l ...

Tsc encounters issues when interacting with AWS services

When attempting to compile TypeScript code into JavaScript using tsc, I encountered constant crashes specifically related to AWS code within the node_modules directory. Despite my efforts to resolve the issue by adding skipLibCheck to my tsconfig file, inc ...

What is the best way to simultaneously receive byte and string data?

Is it possible to concurrently receive byte and string data in an HTTP response? While mixing them in a json is not an option, the concept is clear: private async getFile(): Promise<{ data: Blob, checksum: string }> { return this.http.get('s ...

Angular Input Mask with Validation for Versions 2, 4, and 5 and Beyond

What is the process for validating and displaying validation messages using Angular's Template-driven approach? ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

Angular: Animate newly updated items in a constantly evolving and refreshed list

I'm facing a challenge with my template that includes a simple list with animated items (:enter & :leave animations). @itemAnimation *ngFor="let item of list; There's also an "ADD" button that triggers a modal dialog for users to add new it ...

Using TypeScript generics to create reusable type definitions for reducers

I have a common reducer function that needs to be properly typed. Here's what I have come up with: export interface WithInvalidRows<T extends { [K in keyof T]: InvalidCell[] }> { invalidRows: T; } interface AddPayload<S extends WithInval ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

I'm encountering an issue with my Angular CLI project where it's showing an error message that says "Module cannot be found."

Currently, I am diving into an Angular-cli tutorial. In one of my component TS files, there seems to be a problem with importing a class from another directory as it is not being recognized. Below is the content of my component file (display-user-data-for ...

Creating a carousel with material design aesthetics

I'm working on implementing a carousel in my setup using Angular CLI: 6.0.5, Node: 10.1.0, OS: win32 x64, and Angular: 6.0.3. However, I haven't been able to locate documentation for creating the carousel in Angular's Material Design framewo ...

Issue encountered with Angular Material's md-chips and md-autocomplete: The error message "control.registerOnChange is not a

When attempting to wrap mat-chips and mat-autocomplete into a ControlValueAccessor, I encountered the following errors: InfoEditorComponent.html:17 ERROR TypeError: control.registerOnChange is not a function at setUpModelChangePipeline (forms.js:2701) ...

Troubleshooting npm install failure for firebase packages in Angular

Attempting to replicate the Angular project on my local machine: 1) Clone the project from Version Control 2) Run npm install 3) Installation fails Suspecting an issue with npm itself, I attempt to clear the cache using npm cache clear --force, but it ...