我正在尝试编写一个基本的 Angular 2 应用程序,它使用新版本的 RxJS -> "rxjs": "5.0.0-beta.6"。
我已按照 cookbook 的说明进行操作,尝试创建一个通知服务,我的应用程序的任何部分都可以调用该服务来显示消息。
我遇到的问题是,当我调用 .next()
添加下一个通知时,订阅不会接收到该通知。调用 newNotification
后,this.displayMessage(notification);
行不会运行。我将 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();
}
}
如果有人对其他事情有任何想法可以尝试,那就太好了。 非常感谢
编辑: 完整的 repo 协议(protocol)在这里: https://github.com/sandwichsudo/sentry-material/tree/notifications/src/app
最佳答案
GitHub 在您的存储库中找不到 NotificationService
。
我假设您多次提供 NotificationService
,因此会创建不同的实例,结果是您订阅一个实例并在另一个实例上发送。
确保您有 NotificationService
仅在 bootstrap(AppComponent, [NotificationService, ...])
或仅在您的 AppComponent
中的 providers: [NotificationService]
中。将其从所有其他组件和指令中的 providers: [...]
中删除。
关于angular - RxJS .next() 在 Angular 2 应用程序中默默失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37839198/