Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Angular2 Singleton服务内部的EventListener访问此_Angular_Angular2 Services - Fatal编程技术网

从Angular2 Singleton服务内部的EventListener访问此

从Angular2 Singleton服务内部的EventListener访问此,angular,angular2-services,Angular,Angular2 Services,我正试图观看一个窗口事件来更新单例服务中的变量。我放弃了使用@HostListener,因为它似乎不起作用,而且我在某个地方读到它与服务不兼容。为什么会出现以下代码: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/Rx'; declare let window; @Injectable() export class SharedService { private pr

我正试图观看一个窗口事件来更新单例服务中的变量。我放弃了使用@HostListener,因为它似乎不起作用,而且我在某个地方读到它与服务不兼容。为什么会出现以下代码:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/Rx';

declare let window;

@Injectable()
export class SharedService {
    private progress = new BehaviorSubject(0); // edited according to aluans recommendation
    progressObservable$ = this.progress.asObservable();

    constructor() {
        window.addEventListener('progress', () => {
            this.progress.next(window.sharedService.progress);
        });
    }
}
生成此控制台错误:

未捕获类型错误:\ this.progress.next不是函数


已解决它最终成为一个问题,因为我在将服务附加到的窗口对象上过度使用了进度变量。

没有直接关系,但请不要编写类似于
新行为子对象(0)
的代码。编写
新的行为主体(0)
,让编译器正确地推断类型为
行为主体
,而不是用空洞、无意义的注释来压制它,这样会增加冗长性并降低质量。thx。。我想在这里成为职业选手。真的,谢谢你给我的提示。在看了这一点之后,我有点困惑。我看到您正在引用
window.sharedService.progress
,但您从未将任何内容分配给
window.sharedService
。这可能很好,因为您不应该通过将状态附加到全局变量来共享状态,但这也是一个失败点但这似乎也相当可疑。举办活动的责任是什么?嗨,阿鲁安。。。我用底部的“已解决”更新了我的回答。。结果是因为我在类外访问了progress变量