What is the functionality of the init function?

Ever wondered why console.log("init2"); is printed before console.log("init1");? Also, have you noticed that when console.log(categories); is inside the subscribe function, it displays the correct array on the console, but outside the subscribe function console.log(this.categories); shows undefined? Why does this happen and how can it be fixed?

import { Component, OnInit, OnDestroy } from '@angular/core';
import { CategoryService } from 'src/app/modules/common/services/category.service';
import { CourseService } from '../../services/course.service';
import { mergeMap, map } from 'rxjs/operators';
import { Subscription } from 'rxjs';

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

  categories: any[];
  courses: any[];
  sub: Subscription;

  constructor(private categoryService : CategoryService, private courseService : CourseService) { }

  ngOnInit() {
    this.sub = this.categoryService.getAllcategories()
    .pipe(
      mergeMap(categories => this.courseService.getAllCourses().pipe(
        map(courses => [categories, courses])
      ))).subscribe(([categories, courses]) => {
        this.categories = categories;
        this.courses = courses;
        console.log("init1");
        console.log(categories);
      });
      console.log("init2");
      console.log(this.categories);

  }

  getCoursesByCategory(key: any)
  {
      //console.log(key);
      return this.courses.filter(course => course.category == key)
  }

  ngOnDestroy()
  {
    this.sub.unsubscribe();
  }

}

Answer №1

Utilizing a function that returns an observable, such as your getAllCourses, introduces asynchronicity into the process. This means that if the call is executed quickly, it is possible for init1 to be displayed before init2 or vice versa. This behavior is normal and does not indicate any issues with the code.

To delve deeper into how observables work, check out this resource: https://angular.io/guide/observables

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

Deciphering a mysterious message in Typescript while defining a function for one of my tasks

Currently, I am working with a stack that includes React, TypeScript, and Redux. Unfortunately, I have encountered an issue while using an interface for one of my actions. The error message I received is quite cryptic: Duplicate identifier 'number&apo ...

When executing npm run build, the fonts are not displayed properly in Vite

I'm running 'npm run build' to compile my project, and then I use the 'npm run preview' command to view it. However, some images that I've set as background images in my SCSS file are not showing up. The same issue occurs with ...

What is the reason behind the restriction on using 'this' on the left side of an assignment?

Within the component class, I've been working on this: export class myapp { detail; myarr = ['me', 'myself', 'i']; title = this.myarr[0]; this.detail = this.title ; //error } I'm curious why `this.detail` ...

"Encountering issue with React as old state is being sent instead of updated state when invoking

I am encountering an issue with state variables in my react + mobx + MaterialUI frontend. I have a button that should trigger a function to convert certain state variables into an object and send it to another object for further processing. Strangely, when ...

Setting up a Content Security Policy to allow fetching images from both remote URLs and local sources

My Content-Security-Policy meta configuration looks like this: <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-eval' 'unsafe-inline'; img-src *; style- ...

Are there any methods to incorporate Facebook and Google login into an Ionic progressive web app (PWA)?

After successfully developing an app in Ionic 3 for Android and iOS, I encountered a problem when adding the browser platform. The Facebook and Google login features were not functioning as expected. Despite the assurance from Ionic documentation that the ...

NgRx Store managing tab states

I'm working on integrating a feature similar to browser tabs into my application. At the moment, I am creating a new key in the store for each opened tab and storing the current tab's id separately. This is how my store state looks right now: { ...

Angular 6 powered full stack web application that functions flawlessly on Chrome browser

Currently, I am in the process of constructing a full stack web application focused on data visualization with the use of Angular 6, Django 2.1, Python 3.5, and Postgresql. You can find the code for this project here: https://github.com/shivkiyer/dataviz ...

changing the order of items in a list when using ngFor

I'm currently working on setting up a list-group with list-group-items, but I've encountered a CSS issue caused by Angular when using ngFor on the list-group items. It seems like Angular automatically assigns the bootstrap classes .list-group-it ...

Sticky-top Navbar in Angular5 and Bootstrap4

The "sticky-top" Bootstrap navbar position only functions if the navbar is a direct child of: <body> <header class="sticky-top"> <nav class="navbar navbar-light bg-light p-0"> ... </nav> </header> </bod ...

Can you provide me with the round-the-clock regular expressions for the 'angular2-input-mask' plugin?

Need assistance with inputting 24-hour time format using 'angular2-input-mask'. Currently using the following mask. What is the correct mask for a valid 24-hour time format? this.mask = [/[0-2]/, /^([0-9]|2[0-3])/, ':', /[0-5]/, /[0-9 ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

In Angular interfaces, including an optional ID can result in an error where a number of undefined type cannot be assigned to a parameter expecting

One key feature of my interface is the presence of an optional Id: export interface UserAccount{ // User details id?: number; firstName: string; lastName: string; mail: string; genderId: number; gender?: Gender; password: st ...

Issues with npm audit fixes are leading to the failure of the build process

I've encountered an npm audit issue related to loader-utils and terser in the maintenance of my Angular 14 application. The problem can be found here: https://github.com/advisories/GHSA-4wf5-vphf-c2xc Attempts made to solve it: npm audit fix -force ...

Error: A problem occurred that was not caught in the promise, please investigate further

@Injectable() class MyErrorHandler implements ErrorHandler { handleError(error) { // an error occurred in a service class method. console.log('Error in MyErrorhandler - %s', error); if(error == 'Something went wrong'){ ...

Should Angular Flex Layout be considered a top choice for upcoming development projects?

Should I consider using Angular Flex Layout for upcoming projects, even though it is considered deprecated? Despite its deprecation, there are still a high number of weekly downloads on npmjs.com. I am in the process of starting a new Angular project usin ...

Navigating between child routes in an Angular2 component with two child routers is posing a challenge for me

I have a main component that sets up a Router pointing to 2 child components, each of which also has its own Router setup. Here's an example: Main Component import { Component } from '@angular/core'; import { RouteConfig, ROUTER_DIRECTIVES ...

Are there any potential risks in sticking with Angular 2 instead of upgrading to a newer version?

Our current legacy app has been utilizing Angular 2.4 from the start. The package.json file contains numerous overrides for packages, leading us to use npm install --force during our build process due to peer dependency conflicts and unresolved dependencie ...

I've experimented with binary tree examples and received the output in object form. Now, I'm wondering how I can extract the values from this object and convert them into

Issue Description A tree with N nodes rooted at 1 is given to you. Each node in the tree has a special number Se associated with it. Additionally, each node has a certain Power. The power of each node in the tree is defined as the count of heavy nodes in t ...

What is the best way to execute a method in a component for each iteration in an *ngFor loop in Angular 2

Is there a way to call a method for each iteration of *ngFor and pass the iterated variable as a parameter? For example: <li *ngFor="let element of componentModel | keys">{{element.key}}--{{element.value}}</li> Then, in the component, I have ...