没有在组件中获取 rxjs BehaviorSubject 的更新值

Not getting the updated value of an rxjs BehaviorSubject in a component

我正在开发这个照片编辑器应用程序,其中的更改会自动保存在数据库中。现在我正在尝试添加一个 toast,它会在编辑器数据成功保存到数据库时显示。所以我使用 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);
      })
  }

}

这是照片编辑器组件:

@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 block' 应该在订阅块中!

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