Я пытаюсь написать базовое угловое приложение 2, в котором используется новая версия RxJS -> «rxjs»: «5.0.0-beta.6».RxJS .next() не работает в Angular 2 App
Я следую инструкциям от cookbook, пытаясь сделать службу уведомлений, которые любая часть моего приложения могла вызвать, чтобы показать сообщение.
Проблема, с которой я сталкиваюсь, заключается в том, что когда я вызываю .next()
, чтобы добавить следующее уведомление, это не подхватывается подпиской. Строка this.displayMessage(notification);
не запускается после вызова newNotification
. Я добавил тип BehaviourSubject в свой код (в отличие от темы, используемой в учебнике), и обнаружил, что начальное значение было подхвачено подпиской -был успешно вызван при инициализации. Это заставляет меня думать, что это как-то связано с тем, как/где я вызываю .next() в классе NotificationService
.
Вот соответствующие классы:
NotificationService:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Notification } from '../notification/notification';
@Injectable()
export class NotificationService {
// Observable string sources
private notificationSource = new BehaviorSubject<Notification>(new Notification({message:"test", priority:-1}));
notifications$ = this.notificationSource.asObservable();
newNotification(message: string, priority: number) {
this.notificationSource.next(new Notification({ message, priority }));
}
}
MessageComponent:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Notification } from '../notification/notification';
import { NotificationService } from '../notification.service/notification.service';
import {MdIcon, MdIconRegistry} from '@angular2-material/icon';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'message-container',
styleUrls: ['./app/message/message.component.css'],
templateUrl: './app/message/message.component.html',
directives: [MdIcon],
providers: [NotificationService, MdIconRegistry]
})
export class MessageComponent implements OnDestroy, OnInit {
notification: Notification;
subscription: Subscription;
constructor(
private notificationService: NotificationService) {
this.notificationService = notificationService;
}
ngOnInit() {
this.subscription = this.notificationService.notifications$.subscribe(
notification => {
this.displayMessage(notification);
}, err => console.log(err),() => console.log("completed: "));
}
displayMessage(notification: Notification) {
this.notification = notification;
window.setTimeout(() => { this.notification = null }, 3000);
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
}
Если у кого есть какие-либо идеи по поводу других вещей, чтобы попробовать, что было бы здорово , Большое спасибо
Edit: полный репо здесь: https://github.com/sandwichsudo/sentry-material/tree/notifications/src/app
Большое спасибо за ответ - я обновил URL-адрес репо для правильной ветки https://github.com/sandwichsudo/sentry-material/tree/notifications/src/app. Я проверю, что вы предлагаете, хотя я уверен, что я не загружаю его в любом месте, но симптомы звучат правильно. –
GitHub ничего не нашел. Возможно, сначала нужно индексировать ваш репозиторий. Вы проверяли, не предоставляете ли вы услугу более одного раза? –
Я посмотрел, и я использую NotificationService у поставщиков. Вот файл с начальной загрузкой: https://github.com/sandwichsudo/sentry-material/blob/notifications/src/main.ts и служба уведомления не отображаются. Я не уверен, почему поиск не находит его, это точно в этом файле: https://github.com/sandwichsudo/sentry-material/blob/notifications/src/app/notification.service/notification.service .ts –