Search code examples
angulartypescriptionic2http-postcordova-plugins

Ionic2/Angular2 Can't Call Function within Function


I am using Cordova Facebook Plugin to get user name/email/etc (which works fine) and then want to insert it into my own database. I have tested the posting to DB code by creating a function, tied it to a test button and that works fine too. But when I place the post-2-db code within the fb-login code, it stops executing exactly at my http-post. I do console.log(step1) and see that fine, but I never see console.log(step2) - see my code below:

// LOGIN TO FACEBOOK
doFbLogin(){
    let permissions = new Array();
    let nav = this.navCtrl;
    //the permissions your facebook app needs from the user
    permissions = ["public_profile"];


    Facebook.login(permissions)
    .then(function(response){
      let userId = response.authResponse.userID;
      let params = new Array();

      //Getting name and gender properties
      Facebook.api("/me?fields=name,gender,email", params)
      .then(function(user) {
        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
        //now we have the users info, let's save it in the NativeStorage
        NativeStorage.setItem('user',
        {
          name: user.name,
          gender: user.gender,
          picture: user.picture,
          email: user.email,
        })
        .then(function(){
          // BEGIN INSERT USER TO DB
          // postRequest() {
            var headers = new Headers();
            headers.append("Accept", 'application/json');
            headers.append('Content-Type', 'application/json' );
            let options = new RequestOptions({ headers: headers });
            let postParams = {
              userName: user.name,
              userEmail: user.email,
              userImage: user.picture,
            }

            console.log("STEP 1");

// IT WORKS UP TO THIS POINT

            this.http.post("http://example.com/post.php", postParams, options)
              .subscribe(data => {
                console.log(data['_body']);
                }, error => {
                console.log(error);// Error getting the data
              });
            //}
            // END DB INSERT CODE

// I NEVER SEE THIS CONSOLE LOG BELOW

            console.log("STEP 2");



          // User Reg complete, push them to app
          nav.push(TabsPage);
        }, function (error) {
          console.log(error);
        })
      })
    }, function(error){
      console.log(error);
    });

  }
}

If I take out that chunk of code, everything works fine. I'm very much a beginner to coding and I'd appreciate any thorough layman-level explanation and assistance. Thank you.


Solution

  • As stevenvanc stated,

    replace your

    .then(function(response){
    

    lines with

    .then((response)=>{
    

    otherwise your this will refer to that functions instance