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

I am encountering challenges with React.js implemented in Typescript

Currently, I'm grappling with a challenge while establishing a design system in ReactJS utilizing TypeScript. The issue at hand pertains to correctly passing and returning types for my components. To address this, here are the steps I've taken so ...

Is Angular's forkJoin being phased out?

Upon opening my Angular project today, I came across a warning message that said: The utilization of forkJoin is marked as deprecated: resultSelector is deprecated, it is recommended to use pipe to map instead (deprecation) After searching on Google, I f ...

Is it necessary to enforce a check for surplus properties in the return type of a function

In this particular scenario, the TypeScript compiler does not raise an error when a function returns an object with the type UserProfile even though the expected return type is UserProfileWithNoPermissions. Here's an example: interface UserProfile { ...

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

Setting up the Angular 2 environment with angular-cli: A step-by-step guide

Attempting to configure environment settings using angular-cli following the guide at https://github.com/angular/angular-cli#build-targets-and-environment-files However, even after running "ng build --prod -aot", the output pages continue to display conte ...

What is the best way to align text alongside icons using ng-bootstrap in Angular 8?

I have a set of four icons positioned next to each other, but I want them to be evenly spaced apart. I tried using the justify-content-between class, but it didn't work. How can I achieve this? I'm creating a Progressive Web App (PWA) for mobile ...

Was not able to capture the reaction from the Angular file upload

I've been attempting to upload a single file using the POST Method and REST Calling to the server. Despite successfully uploading the module with the code below, I encounter an error afterwards. Is there anyone who can lend assistance in troubleshooti ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Discover the method of extracting information from an object and utilizing it to populate a linechart component

Object Name: Upon calling this.state.lineChartData, an object is returned (refer to the image attached). The structure of the data object is as follows: data: (5) [{…}, {…}, {…}, {…}, {…}, datasets: Array(0), labels: Array(0)] In the image p ...

Error Encountered: RSA Key Pairs Invalid Signature for JSON Web Token (JWT)

I am facing an issue with my Node.js application (version 20.5.1) regarding the verification of JSON Web Tokens (JWT) using RSA key pairs. The specific error message I am encountering is: [16:39:56.959] FATAL (26460): invalid signature err: { "type& ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Encountering an error of TypeError while attempting to generate a new GraphQL

Currently using Apollo-Server/TypeScript with graphql-tool's makeExecutableSchema() to set up schema/directives. Encountering an error while attempting to add a basic GraphQL Directive: TypeError: Class constructor SchemaDirectiveVisitor cannot be in ...

React: The useContext hook does not accurately reflect the current state

I'm currently facing a dilemma as I attempt to unify data in my app. Whenever I click the button, the isDisplay value is supposed to be set to true; even though the state changes in my context file, it does not reflect in the app. Thank you for your ...

Angular: defining custom module imports - specifying the file path

Is there a more efficient way to specify the path for my imports without using so many dots and forward slashes? Currently, I have something like this: import { Product } from '../../../../../../@core/model/v2/domain/product'; import { ConfigS ...

Invoke a function of a child component that resides within the <ng-content> tag of its parent component

Check out the Plunkr to see what I'm working on. I have a dynamic tab control where each tab contains a component that extends from a 'Delay-load' component. The goal is for the user to click on a tab and then trigger the 'loadData&apo ...

Leveraging Interface in Protractor Testing

As a newcomer to Typescript and Protractor, I have been working with reusable code in various classes. Instead of importing each library class separately into my test class, I am trying to find a way to import just one class or interface that will contai ...

Developing an object using class and generic features in Typescript

I am currently working on creating a function or method that can generate sorting options from an array. One example is when using Mikro-ORM, where there is a type called FindOptions<T> that can be filled with the desired sorting order for database q ...

Error message on Angular 4: "404 - Unable to locate file

Currently, I am working with Angular 4 and attempting to load .csv data. For reference, I have been following this guide: . However, I am facing issues while trying to load the sample.csv file. Despite trying to place the file in src/app, src, or root dire ...

Issue with TypeScript: Error appears when importing express after running "npm i @types/express -D"

Struggling with adding the following line of code in an index.ts file: import express, { Application } from 'express'; Initially encountered an error with "from 'express'", so I ran npm i @types/express -D which fixed that is ...