我正在尝试编写一个基本的 angular 2 应用程序,它使用新版本的 RxJS ->“rxjs”:“5.0.0-beta.6”。
我已按照说明书中的说明,尝试制作通知服务,我的应用程序的任何部分都可以调用它来显示消息。
我遇到的问题是,当我调用.next()
添加下一个通知时,订阅不会收到此通知。this.displayMessage(notification);
调用newNotification
. _ 我将 BehaviourSubject 类型添加到我的代码中(与教程中使用的主题相反),发现初始值已被订阅获取 -this.displayMessage(notification);
在初始化时成功调用。这让我觉得这与我在NotificationService
课堂上调用 .next() 的方式/位置有关。
以下是相关类:
通知服务:
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 }));
}
}
消息组件:
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();
}
}
如果有人对其他事情有任何想法可以尝试,那就太好了。非常感谢
编辑:这里的完整回购: https ://github.com/sandwichsudo/sentry-material/tree/notifications/src/app