1

This is my service class

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

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

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

}

This my component1

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

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

This is my other component 2. leave() is a click event in html.

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

This is my route guard

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();
  }

But I am unable to get data from component1 to component2. or do i need to add the service to any providers in module.

Hans
  • 308
  • 7
  • 20

1 Answers1

1

You need to register the observable before dispatch event:

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$;
  }
}
huan feng
  • 7,307
  • 2
  • 32
  • 56