#angular #lazy-loading #rxjs-observables
#angular #отложенная загрузка #rxjs-наблюдаемые
Вопрос:
Я использую Angular 9. У меня есть корневой NgModule с именем AppModule, который загружает AppComponent, в котором находится основной макет и фрейм моего приложения. В AppModule я также импортирую NotificationComponent, который визуально отображает уведомления, подписавшись на observable в NotificationService (который я также импортирую в AppModule), и на NotificationComponent есть ссылка в HTML-шаблоне загружаемого AppComponent.
Затем я загружаю ProjectDetailModule с отложенной загрузкой, который объявляет ProjectDetailComponent, который также импортирует NotificationService, чтобы он мог запускать уведомления. Однако, когда я запускаю уведомления с помощью NotificationService из ProjectDetailComponent, NotificationComponent не обновляется с этим уведомлением. Есть идеи, где я ошибаюсь?
app.module.ts:
import { AppComponent } from './app.component';
import { NotificationComponent } from './_shared/notifications/notification.component';
import { NotificationService } from './_shared/notifications/notification.service';
@NgModule({
declarations: [NotificationComponent],
imports: [
RouterModule.forRoot([
{
path: 'projects/:id',
loadChildren: () => import('./project-detail/project-detail.module').then(m => m.ProjectDetailModule)
}
])
],
providers: [NotificationService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html:
<div>
<header><img src="assets/logo.png" /></header>
<notification></notification>
<div>
проект-detail.component.ts:
import { NotificationService } from './../_shared/notifications/notification.service';
export class ProjectDetailComponent implements OnInit {
constructor(private notificationService: NotificationService) {}
ngOnInit(): void {
this.notificationService.sendNotification('Project saved');
}
}
уведомление.service.ts:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
private subject = new Subject<any>();
sendNotification(message: string, type: string = null): void {
this.subject.next({ text: message, type: type });
}
getNotification(): Observable<any> {
return this.subject.asObservable();
}
}
notification.component.ts:
import { Component, OnDestroy } from '@angular/core';
import { NotificationService } from './notification.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'notification',
templateUrl: './notification.component.html',
styleUrls: ['./notification.component.css']
})
export class NotificationComponent implements OnDestroy {
public type: string = '';
public message: any;
public show: boolean = false;
public sub: Subscription;
constructor(
private notificationService: NotificationService
) {
this.sub = this.notificationService
.getNotification()
.subscribe(message => {
this.message = message;
this.type = message.type;
this.show = true;
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}