javascript - 类型错误:this.notificationeventservice.shownotification.subscribe
问题描述
组件文件
ngOnInit(): void {
this.subscribeNotification();
}
subscribeNotification {
this.notificationEventService.showNotification.subscribe((data: NotificationData) => {
console.log(data);
});
}
服务文件
import { EventEmitter, Injectable } from '@angular/core';
@Injectable()
export class NotificationEventService {
public notificationCounter = 0;
showNotification = new EventEmitter();
notifySuccess(message: string) {
const data = { type: 'banner', severity: 'success', discreet: false, text: message };
this.showNotification.emit(data);
}
}
组件的规范文件
const notificationEventServiceStub = () => ({
showNotification: () => ({ subscribe: f => f({}) })
});
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [{ provide: NotificationEventService, useFactory: notificationEventServiceStub}]
});
describe('ngOnInit', () => {
it('makes expected calls', () => {
spyOn(component, 'subscribeNotification').and.callThrough();
component.ngOnInit();
expect(component.subscribeNotification).toHaveBeenCalled();
});
});
一旦我监视到这个 ngOnInit 函数,我就会得到
TypeError:this.notificationEventService.showNotification.subscribe 不是函数
解决方案
有一种更好的方法可以做到这一点,您可以使用 behaviorSubject rxjs 并订阅它。
要更改它的值,您必须使用 next() 方法而不是 emit() 方法,这样就可以了。
这是一个如何使用行为主题 RXJS参考链接的示例
希望这会有所帮助,快乐编码:)
推荐阅读
- javascript - Javascript 属性重击
- c# - 在 C# 控制台应用程序中获取鼠标光标位置
- airflow - 全天多个计划的气流计划单 dag
- c# - 找出应用程序使用了哪些表和列
- plsql - 有没有办法测量或监控调度程序作业使用的资源?
- c# - 使用 IQueryable.Where 方法返回所有模型属性,即使为 null 或为空
- google-cloud-platform - 为 config_prd 数据集授予 Airflow 帐户数据查看器权限
- r - 侧边栏面板中没有出现闪亮的小部件
- c++ - 获取未知值和答案
- r - 仅在某些带有 facet_wrap 的子图中释放 y 轴