我正在嘗試編寫一個基本的角度2應用程序,它使用RxJS的新版本 - >「rxjs」:「5.0.0-beta.6」。RxJS .next()在Angular 2中默默地失敗App
我按照cookbook的指示嘗試做出通知服務,我的應用程序的任何部分都可以調用它來顯示消息。
我遇到的問題是,當我撥打.next()
添加下一個通知時,訂閱不會收到此問題。撥打newNotification
後,this.displayMessage(notification);
行不會運行。我將BehaviourSubject類型添加到我的代碼中(與本教程中使用的主題相對),並發現初始值由訂閱獲取--在初始化時被成功調用。這讓我覺得這跟我在NotificationService
類中調用.next()的方式/方式有關。
下面是相關的類:
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();
}
}
如果任何人有其他的事情任何想法去嘗試,這將是巨大的。 非常感謝
編輯: 全回購在這裏: https://github.com/sandwichsudo/sentry-material/tree/notifications/src/app
非常感謝您的回覆 - 我已更新正確分支的回購網址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 –