Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a function that is linked to a test button has been successful. However, when I try to include the post-2-db code within the fb-login code, it stops executing right at the http-post. I have inserted console.log(step1) to check progress, but I never see console.log(step2). Below is the snippet of my code:

// LOGIN TO FACEBOOK
doFbLogin(){
    let permissions = new Array();
    let nav = this.navCtrl;
    // Permissions required by the Facebook app
    permissions = ["public_profile"];


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

      // Retrieving user's name, gender, and email properties
      Facebook.api("/me?fields=name,gender,email", params)
      .then(function(user) {
        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
        // Saving user info in 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");

// CODE EXECUTES 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

// CONSOLE LOG BELOW IS NOT DISPLAYED

            console.log("STEP 2");



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

  }
}

If I remove that section of code, everything runs smoothly. As a programming novice, any simple explanation and assistance would be greatly appreciated. Thank you.

Answer №1

According to stevenvanc's suggestion,

substitute your

.then(function(response){

statements with

.then((response)=>{

or else the reference of this will be directed to the instance of that function

Answer №2

When enclosing that code within a function, the scope of "this" is altered.

this.http.post

"this" now points to the changed execution context which does not have an "http" property attached to it. In strict mode, "this" might even be undefined.

Consider utilizing es6 arrow functions for a fixed "this" or passing in the http object directly.

Answer №3

It appears that an exception is being caused by your call to http.post. This could mean that this or this.http is not defined. Be sure to check your console window for any related error messages.

To handle the exception, you can use a try/catch block:

 try {
    this.http.post("http://example.com/post.php", postParams, options)
          .subscribe(data => {
            console.log(data['_body']);
            }, error => {
            console.log(error);// Error getting the data
          });
   console.log("Successful call!");
 } catch (error) {
  console.log(error);
 }

This code should help identify why the execution is failing at the http.post function call.

Answer №4

Utilize the map function to retrieve the response from the server and then transfer it to the subscribe block.

this.http.post("http://example.com/post.php", postParams, options).map((res: Response) => res.json() || {})
.subscribe( (data) => {
    console.log(data['_body']);
}, error => {
    console.log(error);// An error occurred while fetching the data
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TS18047 jest error: "object may be null"

I'm currently working on a test (jtest) for an angular component, but it keeps failing due to this particular error. Any thoughts on how to resolve this? :) it("should require valid email", () => { spectator.component.email.setValue( ...

The fourth step of the Google Cloud Build process encountered an issue where the use of --openssl-legacy-provider in NODE_OPTIONS was restricted

After successfully running my angular application on a Google Cloud App Engine service for years without any changes to my configuration files or node versions, I encountered an error in my deployment pipeline today: Step #4: node: --openssl-legacy-provid ...

Error occurred when sending form data while uploading a file

Upon trying to upload a file using the formData.append(key, value);, an error message is displayed in the value section: The argument of type 'unknown' cannot be assigned to a parameter of type 'string | Blob'. Type '{}' is ...

"What is the most effective way to utilize and integrate the `setValue` function from react-hook-form within a custom react hook

Struggling to pass setValue to a react hook? In my custom react hook, I need to set values in a form using react-hook-form's setValue. Yet, after migrating from v6 to v7, I'm having trouble figuring out the proper typing for this. This is how t ...

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

The chart is failing to refresh with the latest response information (using Chart.js version 3.2.1 and ng2-charts version 3.0.0-beta.9)

I recently upgraded my project using Chart.js version 3.2.1 and ng2-charts version 3.0.0-beta.9. Initially, everything seemed to be working fine with mock data - the charts were displaying as expected. However, when I switched to testing with real backend ...

When is the right time to develop a new component?

Exploring the strategy behind determining when to create a new component in a web application using angularjs / angular has been on my mind lately. It seems like this concept could apply to all component-based front end frameworks as well. I understand th ...

What is the process for combining an object and a primitive type to create a union type?

Having a tricky time with Typescript and finding the correct typing for my variable. What seems to be the issue? The variable selected in my code can either be of type DistanceSplit or number. I have an array that looks like this: [-100, DistanceSplit, D ...

Adding a local image to Firebase Storage in Angular5 / Ionic3

Uploading images is a breeze using the following method (select input file): import { AngularFireStorage } from 'angularfire2/storage'; @Component({ selector: 'app-root', template: '<div>' + '<input c ...

Automate the process of replacing imports in Jest automatically

Currently, I am in the process of setting up a testbench for a more intricate application. One challenge we are facing is that our app needs to call backend code which must be mocked to ensure the testbench runs efficiently. To address this issue, we utili ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Issue with CanActivateChild not being processed

After logging out and navigating to /, I am facing an issue where the canActivateChild guards are not being executed to redirect to the login page. The main requirement is that none of the application should be accessible without first logging in. Below ...

tsc is not recognizing the configurations in my tsconfig.json file

Running tsc in my project's directory is causing an error to be outputted (as shown below). This is my first attempt at using TypeScript and Node.js. Please consider me as a complete beginner. Operating system: Ubuntu 15.10 64bits NPM version: 2.4. ...

The product details for in-app purchases in Ionic 4 are unable to be viewed until the purchase is complete

After extensively researching and following online tutorials on in-app purchases, I successfully completed the setup on Apple's platform and am now testing the functionality. Everything seems to be working fine, but I'm facing two issues that I n ...

Unable to access property '_lastPathIndex' of an undefined value

In my component spec, I am simulating the Activated Route like this: class ActivatedRouteMock { public paramMap = of(convertToParamMap({ level: 'customer', id: '12345', })); } I have also added this class in the providers ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

Combining Spring Boot and Angular applications for seamless integration

I am trying to connect my Spring Boot application with an Angular application that are running on different servers. When attempting to access REST API from the Angular app, the API call is successful but I encounter an error response on the UI. Acc ...

Achieving Jest integration with Angular 9 in a Storybook setup

We are currently utilizing Storybook 5 alongside Angular 9, with Jest 26 for some of the testing procedures. The issue we're facing arises when using Typescript version below 3.8.0 - a requirement for Angular 9's ng build --prod. This results in ...

Learn how to resubscribe and reconnect to a WebSocket using TypeScript

In my Ionic3 app, there is a specific view where I connect to a websocket observable/observer service upon entering the view: subscribtion: Subscription; ionViewDidEnter() { this.subscribtion = this.socket.message.subscribe(msg => { let confi ...