Search code examples
javascriptangularobservablepass-by-referencesubscription

how to pass one function values to another in - angular 2 service


Need help, to pass the data to one function to another in angular 2 application.

In this application i am getting the data from server

Issue : Unable to send the data to one function to another function in service.ts

Expected: Get the values and read it in second function.

Please note: Since it is a server client integration i dont have a plunker or jsfiddle.

First function

  getDLFolders() {

    return this.http.get(this.url + '/alfresco/api/-default-/public/cmis/versions/1.1/browser/root/sites/' + this.targetSite + '/documentLibrary/' + this.targetFolder + '?/cmisselector=children&succinct=true&alf_ticket=' + this.ticket)
      .map(res => res.json())
      .subscribe(
        resGetRecords => {

          //get objects from document folders
          let objectGroup = resGetRecords.objects;
          let objectIDs = [];
          for (var i = 0; i < objectGroup.length; i++) {

            //push object ID's from folder
            objectIDs.push(objectGroup[i].object.succinctProperties["cmis:objectId"]);
          }
          return objectIDs;
          //this will return []array with following values
          //5645cf45-9b6c-4ad2-ad18-91d24c31f837;1.0
         //4712dc17-0c9f-439f-8577-0c80e52d7afc;1.0
        }
      );
  }

Second function

  getJson() {
   //how to get the getDLFolders function return values
    for (var i = 0; i < objectIDs.length; i++) {
    return this.http.get(this.url + '/alfresco/api/-default-/public/cmis/versions/1.1/browser/root?objectId='+ objectIDs[i] +'&alf_ticket=' + this.ticket)
      .map(res => res.json());
    }
  }

Subscribing in another file

export class UserdashboardComponent implements OnInit {

  details = [];
  records = [];
  errorMsg: string;

  constructor(private _myRecords: AuthService, private _myDocuments: AuthService) { }

  ngOnInit() {
    //get user details, 
    this._myRecords.getPeople()
      .subscribe(
      resGetRecords => {
        // first name, last name
        this.details = resGetRecords;
      },
      resRecordsError => this.errorMsg = resRecordsError
      );

    //get document Libary records of user , 
    this._myDocuments.getJson()
      .subscribe(
      resGetRecords => {
        //debugger;
        // folders
        this.records = resGetRecords;
        console.log(this.records);

      },
      resRecordsError => this.errorMsg = resRecordsError
      );
  }

}

Solution

  • You misused the subscribe method. It doesn't return a value since it's asynchronous but instead a Subscription object here's an example on usage:

    // this returns the Observable<Response> object
    httpGet() {
      return this.http.get('url');
    }
    
    // lets just print it out for now with 2nd function
    secondFunction(data) {
      console.log(data);
    }
    
    // code inside 'subscribe' will execute at a later time when you receive 
    // the response from the server hence it won't return the value like a normal function
    this.httpGet().subscribe(
      (response: Response) => {
        console.log(response); // this will still work
        return response; // this won't work
      }
    );
    
    // if you wish to use the response data you need to call the 2nd function from
    // within the 'subscribe' method
    this.httpGet().subscribe(
      (response: Response) => {
        secondFunction(response); // send data to 2nd function and print it there
      }
    );
    

    Edit:

    As promised I've written some more examples on how to handle async operations in Angular 2/4.

    Here's a plunkr link:

    • first example is simple Say hello where you subscribe in the constructor and emit the value on button click
    • in second example we create a new emitter because plunkr didn't let me import Observable properly and I didn't have much time to write this, then we subscribe and listen for the fake response from the server, when it arrives we handle it by first parsing it from JSON and then alerting it's properties and values

    Second example is how you should handle server response in your service, there're a lot of existing examples like the ones on official angular page:

    Tour of Heroes Angular Tutorial

    Do note that this is how every AJAX request should be handled in Angular.