1

这是我的服务班

export class DataService {
  public isConfirm = new Subject();

  sentIsConfirm(isConfirm: boolean) {
    this.isConfirm.next(isConfirm);
  }

  getIsConfirm(): Observable<any> {
    return this.isConfirm.asObservable();
  }

}

这是我的组件1

 constructor(   
    private dataService: DataService
  ) 
isConfirm: boolean = true;

 leave() {
   this.dataService.sentIsConfirm(this.Confirm);
 }

这是我的另一个组件 2.leave()是 html 中的点击事件。

 confirmation: boolean;
    canExit(): boolean{
     subscription: Subscription;
     this.subscription = this.dataService.getIsConfirm().subscribe((isConfirm) => {
          console.log(isConfirm);
          this.confirmation = isConfirm;
          console.log(this.confirmation);
        });
    }

这是我的路线守卫

export class DeactivateGuardService implements CanDeactivate<SolutionCanvasComponent> {

  component: Object;
  route: ActivatedRouteSnapshot;

  constructor() { }

  canDeactivate(component: Component2,
                route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot,
                nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return component.canExit();
  }

但我无法从组件 1 到组件 2 获取数据。还是我需要将服务添加到模块中的任何提供程序。

4

1 回答 1

1

您需要在 dispatch 事件之前注册 observable:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
  public isConfirm = new Subject();
  public isConfirm$: Observable<any>;

  constructor() {
    this.isConfirm$ = this.isConfirm.asObservable();
  }

  sentIsConfirm(isConfirmed: boolean) {
    this.isConfirm.next(isConfirmed);
  }

  getIsConfirm(): Observable<any> {
    return this.isConfirm$;
  }
}
于 2021-09-03T03:57:54.330 回答