I have a question regarding Angular services, specifically promises and observables, as I am new to them. On my login page, I have a button that, when clicked, should validate the user and generate a token before redirecting to the Home page. However, currently what is happening is that the page redirects before the token is assigned by the service function call asynchronously.
App Data Service
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class AppDataServiceService {
tokenGenerated:any='';
constructor(private http: HttpClient) {
}
getData(){
console.log("Started.. in service");
this.http.get('http://host/url').toPromise()
.then(this.extractData);
}
private extractData(res: Response) {
console.log("completed.. in service");
this.tokenGenerated=res;
return res;
}
}
---------------------------------------------------
Login Component
import { Component, OnInit } from '@angular/core';
import { AppDataServiceService } from '../app-data-service.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login-component',
templateUrl: './login-component.component.html',
styleUrls: ['./login-component.component.css']
})
export class LoginComponentComponent implements OnInit {
constructor(private dataService:AppDataServiceService,private router:Router) {
}
ngOnInit() {
}
submit(){
this.dataService.getData();
console.log('after executing service');
this.router.navigate(['/view']);
};
}
-------------------------------------------------------------
Login HTML
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" >
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" >
</div>
<input type="button" (click)='submit()' value="Login" name="submit"/>
Console output in browser:
Started.. in service
after executing service
completed.. in service
I need assistance in making the HTTP call synchronous using promises. Could you guide me on the correct implementation?