RXJS - 观察变量的变量。

时间:2018-03-30 22:49:25

标签: angular typescript rxjs

我在一个名为isLoading(boolean)的类上有一个变量,其默认值为false。发生操作(http请求)并将变量设置为true。操作完成后,变量将设置回false。我如何使用RXjs来观察这个变量?

this._dataSource = new HttpDataSource(this.service, this.paginator, this.sort, columns);

//this returns false since its before the action that has taken place 

this.isListLoading = this._dataSource.isLoading;

我想要的是RXjs中的这样的东西

this._dataSource = new MCHTTPDataSource(this.takeThisFormService, this.paginator, this.sort, columns);

const intervalId = setInterval(()=>{
    if( !this._dataSource.isLoading ){
        this.isListLoading = false;
        clearInterval( intervalId );
    }
}, 250 );

思考?

1 个答案:

答案 0 :(得分:0)

对于那些关心的人

组件 -

/*
**-------------------------------------------------------------------------------------
** METHOD NAME - ngOnInit
**-------------------------------------------------------------------------------------
*/
ngOnInit() {
    this.paginator.userPageIndex = 5;
    this.dataSource = new MCHTTPDataSource(
        this.tableService,
        this.paginator,
        this.sort,
        this.columnDefinitions
    );
    this.sub = this.dataSource.isLoading().subscribe(( isLoading )=>{
        //notify that loading is done or close loading image etc
        console.log( "still loading", isLoading );
    });
}
/*
**-------------------------------------------------------------------------------------
** METHOD NAME - ngOnDestroy
**-------------------------------------------------------------------------------------
*/
ngOnDestroy() {
    this.dataSource.disconnect();
    this.sub.unsubscribe(); 
}

服务

        public dataLoadingChange = new BehaviorSubject(true);
    /*
        **-------------------------------------------------------------------------------------
        ** METHOD NAME - isLoading
        **-------------------------------------------------------------------------------------
        */
        isLoading():Observable<boolean>{
            return this.dataLoadingChange.asObservable();
        }   
        /*
        **-------------------------------------------------------------------------------------
        ** METHOD NAME - setLoading
        **-------------------------------------------------------------------------------------
        */
        setLoading( loading:boolean ){
            this.dataLoadingChange.next( loading );
        }

//To trigger 
this.setLoading( true | false );