Comunicating between Angular components using observables

September 27, 2021 · 2 min readLucian Ciobanu
Tags:Angular

Once you get used to the fact that an website or an web app can be built on a component structure, the parent to child data passing comes very natural using directives and also the chiald to parent data passing is relatively straight forward via an event emitter. Another quick way of passing data around the app without regarding "family relations" is via services.

I've implemented this way of passing data for a customer recently. The scenario is that after login, the back end returns an observable with the authentication status and the roles the user, information which I then used throughout the app and this is how I did it:

//login.service.ts

export class LoginService {
  public $user: BehaviorSubject<User> = new BehaviorSubject<User>({UserRoles: [], IsUserLoggedIn: false});

  constructor(private http: HttpClient, private router: Router) {}

  public login() {
    return this.http.post<LoginResponse>(environment.apiUrl + 'login', credetials)
      .pipe(
        tap(result => {
          if(result.Success) {
            this.router.navigateByUrl('/home');
          }
          this.$user.next({UserRoles: result.Roles, IsUserLoggedIn: result.Success});
        }),
        catchError(handleError<LoginResponse>())
      );
  }
}

and I'm using the $user observable in the other components:

//home.component.ts

ngOnInit(): void {
  const userRole = this.loginService.$user.subscribe(user => {
    //various usage of the received data from the other components
  }
}

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery