首页 > 解决方案 > 类型错误: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 不是函数

标签: javascriptangularunit-testingjasminekarma-jasmine

解决方案


有一种更好的方法可以做到这一点,您可以使用 behaviorSubject rxjs 并订阅它。
要更改它的值,您必须使用 next() 方法而不是 emit() 方法,这样就可以了。
这是一个如何使用行为主题 RXJS参考链接的示例

希望这会有所帮助,快乐编码:)


推荐阅读