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

Does Angular 8 development mode implement tree-shaking?

I am curious to know if tree-shaking occurs during Angular 8 development mode. When running the following command: ng build I understand that tree-shaking happens when I use the command below: ng build --optimization=true|false ...

Setting checkbox values using patchValue in Angular programming

I'm facing an issue with reusing my create-form to edit the form values. The checkbox works fine when creating a form, but when I try to edit the form, the values don't get updated on the checkbox. Below is the code snippet that I have been worki ...

When converting an NgbDate to a moment for formatting needs, there is a problem with the first month being assigned as 0 instead of 1

I am encountering a challenge with my Ngb-Datepicker that allows for a range selection. To customize the output format, I am using moment.js to convert the NgbDate into a moment object (e.g., Wed Jan 23). One issue I encountered was that NgbDates assign J ...

Warning: The TypeScript version in use may not support all features. The current language level is set to XX in Visual Studio 2019

After installing VS 2019, I noticed that Microsoft.TypeScript.MSBuild 4.2.3 was added. On my Windows 10 OS, I also installed it using NPM in the following way: However, upon opening VS 2019, I encountered the warning below: TypeScript 3.4 feature Curre ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Explore the potential of utilizing Reactive Forms in conjunction with storybook templates

Currently, I am working on developing some custom components and form elements that I intend to include in Storybook. To ensure completeness, I want the stories to utilize FormControl and FormGroup to demonstrate a real-world use case. Here is an example ...

Adding a blank line in an Angular table using primeNG to display database information requires a specific method

In my Angular application, I am utilizing primeNG table to display data fetched from a database. The table comes with 'add' and 'delete' buttons for user interaction. To view the interface, click on this link: https://i.stack.imgur.com/ ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

An issue has occurred: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent

I've been working on implementing Google Auth login with Firebase, but I keep encountering an issue when trying to load another component or page after logging in. I've spent the entire day trying to debug this problem and it's really frustr ...

Switching a parameter from a string to an object will cause Elasticsearch to be unable to properly index the new data structure

I have a collection of items stored in a Firebase database that I am using in conjunction with ElasticSearch for advanced queries. Recently, I had to update the structure of one of the items from a simple string, organizer: "some name", to a more complex ...

Learning the process of interpreting form data in Node.js

I'm currently working with Ionic Angular on the frontend and I am trying to send a formdata that includes a file along with two strings. It seems like the data is being sent successfully, but I am unsure how to access and read this information on the ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

I encountered an issue when trying to dynamically add a text field in Angular 2. The error message received was "ERROR TypeError: Cannot read property '0' of

I am currently utilizing Angular2 in my project, and I am attempting to dynamically add a text field. However, I keep encountering an error: Error Message (TS): ngOnInit() { this.myForm = this._fb.group({ myArray: this._fb.array([ ...

Error occurred due to changed expression after initial checking in Angular's dynamic template management

I am looking for a way to dynamically manage templates by showing or hiding certain views based on parameters that change after receiving WebSocket messages or user interactions. I currently use ngIf for this purpose, but sometimes when the view is reloade ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Why doesn't the primitive value get updated in Angular Service?

I've been exploring the functionality of Angular Services, and I'm encountering an issue with the heroCounter (number) not updating correctly while the hero array does. When I add a new dummy hero, I expect the heroCounter to increment accordingl ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

"Utilizing HTML aids for creating text input fields and adding line breaks

public string BannerText {get;set;} public void SetBanner() { BannerText = "This is line 1. \nThis is line 2." } on my webpage, I am displaying it like this: <div> <h1><%: Model.BannerText %></h1> </div> The issue ...

billboard.js: The 'axis.x.type' property is conflicting with different data types in this context

axis: { x: { type: "category" } }, An issue has arisen: The different types of 'axis.x.type' are not compatible with each other. The value of 'string' cannot be assigned to '"category" | &qu ...