Struggling to fetch data using Angular 11 as an observable? Issues arise when using async or JSON pipe in a lazy loaded component/module, resulting in errors displayed in the console.
The module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TestRoutingModule } from './test-routing.module';
import { TestComponent } from './test.component';
@NgModule({
declarations: [TestComponent],
imports: [CommonModule, TestRoutingModule],
})
export class TestModule {}
The component:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {
user$: Observable<any>;
constructor(private http: HttpClient) {}
ngOnInit() {
this.user$ = this.http.get('https://jsonplaceholder.typicode.com/users/1');
}
}
The Test component html:
<pre>{{ user$ | async }}</pre>
The App Module:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { CommonModule } from '@angular/common';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [AppComponent],
imports: [
CommonModule,
AppRoutingModule,
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
app-routing.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { IndexComponent } from './features/index/index.component';
const routes: Routes = [
{ path: 'index', component: IndexComponent },
{
path: 'test',
loadChildren: () =>
(
import(
'./features/test/test-routing.module'
)
).then(p => p.TestRoutingModule),
}
{ path: '', redirectTo: '/index', pathMatch: 'full' },
{ path: '**', redirectTo: '/index' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
My package.json is:
"dependencies": {
"@angular/animations": "~11.0.9",
...
// The rest of the package.json contents are still the same
My tsconfig.json:
{
...
// The content inside tsconfig.json remains unchanged
Troubleshooting steps taken so far:
- Added CommonModule into both the lazy loaded module and AppModule (no success)
- Updated Angular to version 11.2.0 (still encountering issues)
An observation made regarding the getPipeDef$1 function from core.js indicated that the registry is null (refer to image):
https://i.sstatic.net/vc6QX.png
Any suggestions on resolving this issue would be greatly appreciated. Thank you!