0

I have a component "CompA" which has a function named getDocID(), that takes a value from the template on a mouse click and then gets an object asynchronously after doing some query in the firebase with that value.

The problem is, I need to pass this object to another component "CompB" on routing.

This is how my code is looking like right now:

Template:

 <a (click)="getDocID(doc.docID)">Edit this Document</a>

Component:

getDocID(docID){
  this._docEditService.getSingleDoc(docID, singleDoc => {

    //here will come the async singleDoc object which I need to pass to the edit-doc route

  });
  this._router.navigate(['edit-doc']);
}

Service:

    getSingleDoc(docID, callback) {
    this.userSingleDoc = this.af.database.list('docs', {
      query: {
        orderByChild: 'docID',
        equalTo: docID
      }
    });

    this.userSingleDoc.forEach(element => {
      for (var el in element) {
        var x = element[el];

        var singleDoc = {
          docID: x['$key'],
          docTitle: x.docTitle,
          docDescription: x.docDescription,
          timestamp: x.timestamp,
        }
        callback(singleDoc)
      }
    });
  }
Tanvir Hossain Khan
  • 537
  • 1
  • 7
  • 22
  • Have you tried passing an object to another component using service? It's a common pattern that you use service for communication between components. [See the answer for more details](https://stackoverflow.com/a/44865817/2327713) – Bohdan Khodakivskyi Dec 25 '17 at 05:44
  • I have tried that. But since the object creation is async, the Another Component (Comp B) loads before the object is there, resulting in undefined values. I have tried calling the object from the service in the Constructor, in ngOnInit, and ngAfterViewInit. No luck till now. – Tanvir Hossain Khan Dec 25 '17 at 07:05
  • That's expected because by the time component is mounted the data is not there yet. To achieve this you need **ngOnChanges** lifecycle hook. See my answer here and let me know if it's helped: https://stackoverflow.com/a/47695003/2327713 – Bohdan Khodakivskyi Dec 25 '17 at 07:36
  • use a service, navigate to other component after setting the object in the service. – AT82 Dec 25 '17 at 08:38

0 Answers0