Encountering "undefined" response while retrieving data from service in Angular 2

I'm experiencing an issue with my Angular 2 application where I am making an HTTP call in a service and trying to return the response back to the component. However, when I console log the response, it shows as "undefined". I have added a timeout to ensure that the HTTP request completes before logging the response, but it still doesn't work. As a newcomer to Angular 2, I would greatly appreciate any assistance from someone who can help me troubleshoot this. Below is my service code:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { LoginComponent } from './login/login.component';

    @Injectable({
      providedIn: 'root'
    })
    export class LoginService {    

      rootUrl = 'https://dev-510009.oktapreview.com/'
      constructor(public _http: HttpClient){

      }
      primaryVerify1(userData) {
        let data = {
          "username": userData.username,
          "password": userData.pass,
          "options": {
            "multiOptionalFactorEnroll": true,
            "warnBeforePasswordExpired": true
          } 
        };
       this._http.post(this.rootUrl + "api/v1/authn", data, {
         headers: {
           'Content-type': 'application/json'
         }
       }).subscribe(response => {
         if(response.status == 'SUCCESS'){
          let primaryverifydata = response
           console.log("primaryverifydata", primaryverifydata)
           let data1 = {
              "factorType": "token:software:totp",
              "provider": "GOOGLE"
           }
           this._http.post(this.rootUrl + "api/v1/users/"+ primaryverifydata._embedded.user.id + "/factors", data1,
           {
             headers: {
               'Content-type': "application/json",
               'Authorizatio`n' :'SSWS 00e1Wq_tDwvikJt2ZufC0DgW58JX61R6BEQriGsvtl',
               'Accept': "application/json"
             }
           }).subscribe(response => {
             console.log(response)
             let enrollResponse = response;
             if(response.status = 'PENDING_ACTIVATION'){
               window.open(enrollResponse._embedded.activation._links.qrcode.href, '_blank')
               return response;
             }

           })
         }
       })
      }


}

My component code:

    import { Component, OnInit } from '@angular/core';

    import { LoginService } from '../login-service.service';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css'],
         providers: [LoginService],
    })
    export class LoginComponent implements OnInit {
         userData: object;
      pass: any;
        enrollResponse: object;
    constructor(private loginservice: LoginService) {
        this.userData = {};
        this.pass = "";
        this.enrollResponse = {}
       }
        ngOnInit(){
          /*  this.enrollResponse = this.loginservice.primaryVerify;
            console.log(" this.enrollResponse",  this.enrollResponse)*/
        }
        primaryVerify(){
            let some = this.loginservice.primaryVerify1(this.userData);
            setTimeout(() => {
                 console.log("this.enrollResponse", some)
            },5000)

        }
    }
Kindly note: primaryVerify() gets fired when user clicks on submit button.

Answer №1

  1. To ensure consecutive HTTP requests are made one after another, utilize switchMap within your service method primaryVerify1(). This will replace the previous observable.

  2. Avoid subscribing within the service; instead, subscribe in your component and simply map the results passed from the service (i.e., return response from the service). Take note of the three return statements present in the code below.

  3. The use of setTimeout() is unnecessary in the component; opt to subscribe to primaryVerify1() instead.

Service code :

primaryVerify1(userData) {
        ...........
       return this._http.post(this.rootUrl + "api/v1/authn", data, {
         headers: {
           'Content-type': 'application/json'
         }
       }).pipe(switchMap(response => {
         if(response.status == 'SUCCESS'){
          ...............
           return this._http.post(this.rootUrl + "api/v1/users/"+ primaryverifydata._embedded.user.id + "/factors", data1,
           {
             headers: {
               'Content-type': "application/json",
               'Authorization' :'SSWS 00e1Wq_tDwvikJt2ZufC0DgW58JX61R6BEQriGsvtl',
               'Accept': "application/json"
             }
           }).pipe(map(response => {
             ...........
               return response;
             }))

           })
         }
       }))
    }

Component:

primaryVerify(){
     let result = this.loginservice.primaryVerify1(this.userData).subscribe(data => console.log(data));
}

Answer №2

primaryVerify1 does not send back a response, so it's expected to be undefined.

To fix this issue, you can implement a callback function or use a Promise. Here is an example:

primaryVerify1(userData, callback) {
  ...
         let enrollResponse = response;
         if(response.status = 'PENDING_ACTIVATION'){
           window.open(enrollResponse._embedded.activation._links.qrcode.href, '_blank')
           callback(response);
         }

You can utilize it in this manner:

let some = this.loginservice.primaryVerify1(this.userData, function(res) {
  console.log("this.enrollResponse", res);
});

While this solution may not handle errors perfectly (consider adding error handling at each possible point), it serves as a good starting point.

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

Guide to incorporating d.ts file for enhancing intellisense in VS Code using a method akin to the NPM approach

In my nodejs project (in JS), I find myself relying heavily on node global variables. Despite receiving warnings against using globals, everything works well except for one thing: The lack of intellisense for globals. Every time I need to use a global fu ...

Using three.js lookAt() to align a local axis that is not the positive Z axis towards a different object

Currently, I am in the process of developing an application in which a character (depicted as a cone shape for now) is positioned on a specific surface (currently represented by a cylinder placed horizontally). My goal is to have the character's feet ...

Instructions on enabling German users to input numbers in German format within React JavaScript

Our project involves creating an application that caters to both German and English users. How can we enable German users to input numbers in their format (using "," as a decimal point and "." as a thousand separator), so that when they tab out of the inp ...

Efficient PHP caching solution for optimizing JavaScript and CSS performance

I'm facing a unique challenge that I can't seem to solve through typical Google searches. I'm in the process of consolidating all my javascript and css into separate php files using require_once() to pull in the content. The structure of my ...

Content placed in a div element via JavaScript will not wrap onto a new line

I recently created a div using JavaScript with the code mydiv.textContent="blahblahblahblahblahblah";. Although I have set the width of mydiv to 100px, the text string assigned to the div continues to run in one line without dropping down to the next lin ...

How can I use JavaScript to modify the style of the first unordered list (ul) element without affecting the

function displayMenu(){ var parentElement = document.getElementById("menuItem1"); var lis = parentElement.getElementsByTagName("ul"); for (var i = 0; i < lis.length; i++) { lis[i].setAttribute("style","display: block"); } } When the button is clicke ...

Tips for navigating through lengthy webpages using the jQuery onepage-scroll plugin

I recently came across a fantastic plugin called onepage-scroll that almost perfectly fits my requirements. However, I have encountered an issue. Some of my pages, defined within <section> tags, are larger than a single screen. Is there a way to cust ...

Tips for updating Okta token when there are changes to claims

Currently, my react app is successfully using oauth (specifically okta), but I am encountering a problem. Whenever I modify the claims in the authorization server, the changes are not reflected in the app until the token expires or I perform a logoff and ...

Sharing information from one component to another in ReactJS can be achieved by using props or the context API. By

There are two important files - Sidebar and UserDataElements. The goal is to showcase the data from UserDataElements in the Sidebar. Here's what I've attempted so far: This is the primary file where both files are being fetched. <Sidebar&g ...

Managing jquery values with cookies for loading, saving, and resetting

I recently implemented screen adjustments on my website using scrollbars. I utilized this example as a reference. Below is the code snippet... HTML CODE: <h1>Image Editor with CSS Filters and jQuery</h1> <!--Form for collecting image URL ...

How can I continuously send RS232 data from a Python script running in a while loop to HTML using AJAX?

Just getting my feet wet with AJAX and serial ports, looking for some guidance. I have a device that transmits data through an RS232 port to a web server. My goal is to continuously display this data on my website. To make this happen, I've written ...

Retrieve the URL using a jQuery request in the P&G RFC

Hello, I am facing a problem with my AJAX URL requests. The issue is that when I include an RFC that contains the character "&" in it, only "P" is returned instead of the complete value. For example: Http://......../Get?RFCRec=P&G5609219R2 When the ...

Leveraging LevelGraph with MemDOWN

I've been experimenting with using LevelGraph and MemDOWN together, but I've noticed that my put and get queries are significantly slower compared to using the filesystem directly with LevelUP. It seems like there might be some mistake in my setu ...

Having issues with displaying options in Select2 within a Vue Component?

I have successfully created a Vue component that generates options for a select dropdown as shown below: <select ref="subdomain_id" name="subdomain_id" id="newEvidenceSubdomain" class="form-control" :class=&qu ...

Using Conditionals in React Props

In the process of developing a component that requires two props, inside and position, I've encountered an interesting dilemma. When inside is set to true, then position is limited to left or bottom. However, if inside is set to false, then position c ...

Running a TypeScript program that has been compiled with module resolution is not working as expected

I am currently in the process of compiling a TypeScript file with the following code: import { magic } from 'lib/magic'; magic(); The file structure looks like this: ./src/ main.ts lib/ a/magic.ts b/magic.ts Within ...

I am encountering a JSON parsing error while trying to implement jQuery autocomplete, despite using a local array

I'm attempting to implement the jQuery autocomplete feature on a WordPress website. My ultimate goal is to link the input field to an ajax request that will retrieve data from a database. However, I've encountered an unusual error when trying to ...

When utilizing tabler angular, it is important to ensure that it is listed in your tsconfig under the 'files' or 'include' property

I'm currently exploring the usage of Angular Tabler @tabler/angular-core @tabler/angular-ui @tabler/angular-styles @tabler/angular-forms Upon npm installing all these packages and executing ng serve, I encountered the following error: Argument of t ...

Executing JQuery and Ajax calls within a loop

Can I dynamically change the variable in ("xxxxx").html(data) inside a for loop? I've been struggling to figure this out. My goal is to populate an HTML table with JSONP data from multiple ajax calls within a loop, where the URL changes each time. Wh ...

Prevent UI-Router from Interacting with the browser's window location

Seeking input on a unique challenge regarding UI-router in AngularJS. In the process of migrating a project to Angular JS, I encountered an issue with multiple panels being dynamically loaded onto a page using AJAX and managed by jQuery History. Each pane ...