The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been assigned yet. How can I resolve this problem? Thank you for your help.

This is the implementation of the ngOnInit method:

ngOnInit() {

    // Retrieve the user Id by executing a service method.
    this.authorizeService.getUser().subscribe(data => {
      this.userId = +data.sub;
    });

    // Obtain the list associated with the user by passing the userId as a parameter.
    this.service.getList(this.userId).subscribe(data => {
      this.list = data;
    })
  }

An error message stating cannot read property sub of null appears. Despite nestling these two calls and being logged into the account, the issue persists.

I have attempted to nest the subscriptions using switchMap or mergeMap, but I am struggling with their syntaxes.

The getUser() service method:

  public getUser(): Observable<IUser | null> {
    return concat(
      this.getUserFromStorage().pipe(filter(u => !!u), tap(u => 
      this.userSubject.next(u))),
      this.userSubject.asObservable());
  }

The getList() service method:

  getList(userId: number): Observable<number[]> {
    return this.http.get<number[]>("myApiURLhere?userId=" + userId)
      .pipe(
        retry(1),
        catchError(this.errorHandler)
      );
  }

Error details:

Argument of type '(data: IUser) => void' is not assignable to parameter of type '(value: IUser, index: number) => ObservableInput<any>'.

Type 'void' is not assignable to type 'ObservableInput'

Answer №1

Can you please share the specific Angular version that you are using? Providing some code snippets would allow us to assist you better.

Answer №2

When working with asynchronous functions, it's best to utilize the switchMap operator from RxJS to simplify handling multiple subscriptions:


import { switchMap} from 'rxjs/operators';

ngOnInit() {
 this.authorizeService.getUser().pipe(
  switchMap(data => {
   this.service.getList(+data.sub)
})).subscribe( data => this.list = data)
}

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

Where do you see the Sys.require, ASP.NET AJAX loader script heading in the future?

Is the future of this script uncertain, or is it on its way out to be replaced by a different component? I rely heavily on its functionality and am curious if there is a superior alternative or what lies ahead for it... Just to clarify, I am referring to ...

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

What is the mechanism behind property binding in Angular 2? Can you explain what is happening in this specific scenario?

Being a novice in the realm of Angular 2, I find myself grappling with doubts related to property binding. While this particular example seems to work fine, I can't help but wonder about what exactly goes on behind the scenes. Within my component vi ...

Node.js and Typescript encountering issues resolving module paths

I am brand new to both Express and Typescript. I recently inherited a project that utilizes express for an API. I need to make some modifications, but I am having trouble transpiling the code. I have exhausted all my options and now I'm seeking help h ...

What steps are required to customize a pre-existing DevExtreme JQuery DataGrid that was initially built in a cshtml file using Typescript?

I'm currently developing a web application using DevExtreme JQuery. Within the frontend, I have set up a DataGrid in a cshtml file. With DevExtreme functionality, it's possible to include an Add Button to the DataGrid that triggers a popup for in ...

A new form of error emerges: "InvalidOperation: outcomes.map lacks functionality. Operation.displayStaff

I encountered an error while attempting to display API data using a ReactJS application. I followed the code below, but it keeps showing the following error: TypeError: results.map is not a function Function.renderemployeeTable In this case, `res ...

To handle the input field efficiently in Angular, consider utilizing two <input type="radio"> elements

I am facing a challenge in my Angular 5 project where I have two radio buttons and need to dynamically update the value of formControlName and placeholder for an input field based on the selected radio button. How can I tackle this issue? <div clas ...

Angular 11 error: Unable to access 'scrollHeight' property of null object due to TypeError

I'm hoping that someone out there can assist me in solving this puzzling issue. I am trying to obtain the full scrollHeight of the page, but for some reason, I am only getting a third of it. setSize() { let DOMScrollable = this.elementRef.nativeEl ...

"Troubleshooting Primeng's p-table filter issue when using an editable FormArray - encountering problems with the

I'm encountering a problem with the filter functionality on primeng p-table when using formarray controls. The filter doesn't seem to work correctly, so I tried registering a custom filter and testing it. However, I found that the value is null f ...

Azure ASP.NET REST Web Service Call not being processed

After working with the new Azure Machine Learning Service, I successfully created a web service from my model. When I use a HTTPS tool to POST to the service, I receive the expected results. The issue arises when trying to integrate my ASP.NET code with t ...

What could be causing a custom Angular library to fail to compile after being published on npm?

I recently launched a library that I created for my team to expedite the process of developing applications specifically for the Internet of Things (IOT) sector. However, I have encountered an issue where the library compiles without errors in the demo pro ...

Yes, it's not able to retrieve the value from headlessui combobox

I have encountered an issue while using the Headlessui combobox component in conjunction with Yup. Despite successfully storing the selected value in the selectedMemory state variable, Yup consistently generates a required error message. I seem to be overl ...

Protractor test stalls when waiting for disabled element using async/await instead of control flow

We are currently designing end-to-end tests using async/await methodology for easier debugging. However, we have encountered an issue with a particular test that hangs on the line: await browser.wait(ExpectedConditions.presenceOf(appPage.getLogo())); I a ...

Set Chartjs2 data to display as a doughnut chart starting from 0

When working with a doughnut chart and having data values set to 0, it is important to ensure that the default chart still displays with equal size parts. To achieve this, one can utilize the beginAtZero option in JavaScript: JS scales: { yAxes: [{ ...

Unexpected behavior: Angular post request does not include the expected request body

Embarking on my initial solo Angular project... I am endeavoring to make a post request to my freshly created web service and have implemented the following code: headers = new HttpHeaders( {'Content-Type':'text/plain'} ); l ...

Having trouble with browser freezing when using array push in Angular 4? Looking for a solution to fix this issue?

In my logsCompoment.ts file, there is an array called logs where I store new log entries and display them on the HTML page using ngFor directive. I achieve this by handling incoming data in the following manner: this.socket.on('newline', (data) ...

Unique validator for form fields in Angular Reactive Forms when in edit mode

In my current project, I am developing an Angular 8 application using Reactive Forms. The form in question serves both create and update operations with a set of controls. Here is the code snippet for initializing the form: this.form = new FormGroup({ ...

The traditional function does not have access to a reference to this

For my web development project with Angular 9, I needed to add a typeahead feature using ng bootstrap typeahead. The code provided below worked perfectly: search = (text$: Observable<string>) => text$.pipe( debounceTime(150), disti ...

How is it possible to leverage the CDN URL mechanism for package management when working with Typescript?

Is it possible to use a CDN URL pointing mechanism to resolve packages in Typescript? One example is the Material Icon package installation, which can be included using the following code: <link rel="stylesheet" href="https://fonts.googleapis.com/icon? ...

I'm facing challenges in getting my server action to trigger. The error message that keeps popping up is unexpected submission of a React form

I have been working on developing a registration form using Next.js, react-hook-form, and Zod. Here is the code snippet for the form component: 'use client'; import { z } from "zod"; import { useRef } from "react"; import { u ...