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();
}
}