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.