我试图显示用户在标头中的通知数量,并每隔5秒轮询一次。
我有通知服务:
export class NotificationService {
readonly baseUrl = `${environment.apiUrl}/notification`;
constructor(private http: HttpClient) { }
public getNotificationCountForUser(userid): Observable<number> {
return Observable.interval(5000)
.switchMap(() => this.http.get<number>(this.baseUrl + '/getNotificationCountForUser?UserId=' + userid));
}
我正在尝试将此加载到我的标题中的BehaviorSubject
:
export class HeaderComponent implements OnInit {
private notificationCountSubject = new BehaviorSubject<number>(0);
notificationCount = this.notificationCountSubject.asObservable().share();
constructor(private, private notificationService: NotificationService,
private router: Router) { }
ngOnInit() {
this.notificationCountSubject.next(this.notificationService.getNotificationsForUser(this.currentUser.id));
// I get the user id from a separate function, have left it out in my question
}
})
}
我的this.notificationCountSubject.next
语法不正确,我应该传递一个号码,但我传递的是Observable
而我不确定如何处理此问题。< / p>
我应该在我的服务中加载BehaviorSubject
而不是我的组件吗?然后我会通过什么?
更新
我已尝试将此全部内容放入我的通知服务中:
export class NotificationService {
readonly baseUrl = `${environment.apiUrl}/notification`;
private notificationCountSubject = new BehaviorSubject<number>(0);
public readonly notificationCount = this.notificationCountSubject.asObservable();
constructor(private http: HttpClient) { }
public getNotificationCountForUser(userid): Observable<number> {
return this.notificationCountSubject.next(
Observable.interval(5000)
.switchMap(() => this.http.get<number>(this.baseUrl + '/getNotificationCountForUser?UserId=' + userid))
);
}
但得到&#39;类型&#39; Observable&#39;不能分配给&#39;数字&#39;。&#39;
类型的参数