[Fixed] How to pass on object created in function?

Issue

  login() {
this.dbService.createRemoteDB();
this.dbService.createLocalDB();
let user;
this.userService
  .getUserFromRemoteDb()
  .then((userDoc: any) => {
    // Need to pass user to the next component
    user = userDoc;

    return this.syncService.getSyncDoc(user._id);
  })
  .then((syncDoc: any) => {
    return this.syncService.downloadData(user, syncDoc);
  });

}

My question is how can I pass "user" on to a different component? So I don’t have to get the user from the database again.

Solution

You might have to create a quick caching service with RxJS Subject. Note that there are better alternatives to be found. As noted, this would be the quickest way.

I’ll use ReplaySubject with buffer 1 since it can "hold" the current values and emit immediately to future subscribers.

cache.service.ts

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

@Injectable({ providedIn: 'root' })
export class CacheService {
  private user: ReplaySubject<any> = new ReplaySubject<any>(1);  // <-- buffer 1
  public user$: Observable<any> = this.user.asObservable();
  
  cacheUser(user: any) {
    this.user.next(user);
  }
}

Login component

constructor(private cache: CacheService) { }

login() {
  this.dbService.createRemoteDB();
  this.dbService.createLocalDB();

  this.userService.getUserFromRemoteDb()
    .then((userDoc: any) => {
      this.cache.cacheUser(userDoc);
      return this.syncService.getSyncDoc(user._id);
    })
    .then((syncDoc: any) => {
      return this.syncService.downloadData(user, syncDoc);
    });
}

Other component

user: any;

constructor(private cache: CacheService) { }

ngOnInit() {
  this.cache.user$.subscribe(user => {
    // use `user` from login
  })
}

Leave a Reply

(*) Required, Your email will not be published