我正在尝试编写一个基本的角度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 –