没有得到组件中rxjs BehaviorSubject的更新值



我正在研究这个照片编辑器应用程序,其中更改自动保存在数据库中。现在我正在尝试添加一个祝酒词,当编辑器数据成功保存到db时显示。所以我使用RxJS的BehaviorSubject来实现这一点。

请注意,编辑器更改首先被发送到一个名为DataProcessService的服务,在那里它被处理,然后在另一个服务中进行API调用。同样在DataProcessService中,我已经为BehaviorSubject设置了逻辑。

DataProcessService中的代码现在看起来是这样的:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
class DataProcessService {
private toast = new BehaviorSubject<boolean>( false );
currentToastState = this.toast.asObservable()
private constructor( private apiService: ApiService ) {}
changeToastState( state: boolean ): void {
this.toast.next( state );
}
process( data ) { 

// got rid of data processing for simplicity

this.apiService.postData( data )
.then( response => {
console.log('Success');
this.changeToastState( true );
})
.catch( error => {
console.log('Error: ', error);
})
}
}
这是PhotoEditorComponent:
@Component({
selector: 'editor-page',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
class PhotoEditorComponent implements OnInit {
@ViewChild('toast');
toast: ToastComponent;
isToast: boolean;
private constructor( private dataProcessService: DataProcessService ) {}
ngOnInit(): void {
this.dataProcessService.currentToastState.subscribe( state => {
this.isToast = state;
});
console.log( 'Log 1: ', this.isToast );
if ( this.isToast ) {
console.log( 'Log 2: ', this.isToast );
this.successMessage = 'Saved successfully!;
this.ref.detectChanges();
this.toast.show();
this.dataProcessService.changeToastState( false );
}
}
}

请注意,Log 1false当我刷新页面。当编辑器有变化时,它不会把它变成true或任何东西。Log 2从不触发' ' '

这个'if块'应该在订阅块我猜!

if ( this.isToast ) {
console.log( 'Log 2: ', this.isToast );
this.successMessage = 'Saved successfully!;
this.ref.detectChanges();
this.toast.show();
this.dataProcessService.changeToastState( false );
}

最新更新