I have a very simple test app made of 2 components
- AppComponent
- ListComponent
Both components have the same behavior: at load time they show a list of items coming from an Observable using async pipe. AppComponent in addition has a button and a RouterOutlet where it loads ListComponent as soon as the button is clicked.
When this code is compiled for development, i.e. with ng build, everything works as expected. When the same code is compiled for prod, i.e. ng build --prod, then the behavior is different. In this second case, if I click the button to go to ListComponent, the Observable of ListComponent DOES NOT EMIT anymore at the load of the page.
The code is the following (I have also a Stackblitz example where the problem though does not occur)
ListComponent
@Component({
selector: 'app-list',
template: `
<input #searchField type="text">
<div *ngFor="let item of itemsToShow$ | async">{{item}}</div>
`,
})
export class ListComponent implements OnInit, AfterViewInit {
@ViewChild('searchField', {static: true}) searchField: ElementRef;
search$: Observable<string>;
itemsToShow$: Observable<string[]>;
ngOnInit() {}
ngAfterViewInit() {
this.search$ = merge(concat(of(''), fromEvent(this.searchField.nativeElement, 'keyup'))).pipe(
map(() => this.searchField.nativeElement.value)
);
this.itemsToShow$ = this.itemsToShow();
}
itemsToShow() {
let itemAsLocalVar: string[];
return of(ITEMS).pipe(
delay(10),
tap(items => itemAsLocalVar = items),
switchMap(() => combineLatest([this.search$])),
map(([searchFilter]) => itemAsLocalVar.filter(i => i.includes(searchFilter))),
);
}
}
AppComponent
@Component({
selector: 'app-root',
template: `
<input #searchField type="text">
<div *ngFor="let item of itemsToShow$ | async">{{item}}</div>
<router-outlet></router-outlet>
<button (click)="goToList()">List</button>
`
})
export class AppComponent implements OnInit, AfterViewInit {
@ViewChild('searchField', {static: true}) searchField: ElementRef;
search$: Observable<string>;
itemsToShow$: Observable<string[]>;
constructor(
private router: Router,
) {}
ngOnInit() {}
ngAfterViewInit() {
this.search$ = merge(concat(
of(''),
fromEvent(this.searchField.nativeElement, 'keyup')
)).pipe(
map(() => this.searchField.nativeElement.value)
);
this.itemsToShow$ = this.itemsToShow();
}
itemsToShow() {
let itemAsLocalVar: string[];
return of(ITEMS).pipe(
delay(10),
tap(items => itemAsLocalVar = items),
switchMap(() => {
return combineLatest([this.search$]);
}),
map(([searchFilter]) => itemAsLocalVar.filter(i => i.includes(searchFilter))),
tap(i => console.log(i))
);
}
goToList() {
this.router.navigate(['list']);
}
}
Any idea of what is going wrong is very much appreciated.
Any idea of