我正在開發這個照片編輯器應用程式,其中更改會自動保存在資料庫中。現在我正在嘗試添加一個 toast,當編輯器資料成功保存到 db 時會顯示。所以我正在使用 RxJSBehaviorSubject來實作這一點。
請注意,編輯器更改首先發送到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 1是false我重繪 頁面的時候。當編輯器發生變化時,它不會將其轉換為true或任何其他內容。Log 2從不開火```
uj5u.com熱心網友回復:
我猜這個'if block'應該在訂閱塊中!
if ( this.isToast ) {
console.log( 'Log 2: ', this.isToast );
this.successMessage = 'Saved successfully!;
this.ref.detectChanges();
this.toast.show();
this.dataProcessService.changeToastState( false );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/479662.html
