My Service
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { HttpClient,HttpParams } from '@angular/common/http';
@Injectable()
export class UserService {
constructor(private http: HttpClient) { }
isAdmin;
getLogIn(email:string,password:string):Observable<boolean>{
let params = new HttpParams().set("userEmail",email).set("userPassword", password);
return this.http.get<boolean>("http://localhost:8080/user/login",{params: params});
}
}
My Subscribe call
email:string="";
password:string="";
adminFlag:boolean=false;
login(event: any) {
console.log(this.adminFlag);
this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
console.log(this.adminFlag);
if(this.adminFlag){
console.log("INSIDE IF")
this.router.navigate("../../home");
}
}
When i log in data var in console I am getting raw data as
true
but i couldn't assign it to this boolean "adminFlag" it is changed to undefined
Anything I missed...???
the API is returning a boolean..I need that boolean to be assigned...
HTTP GET is an asynchronous request . Which means you are reading the variable adminFlag
before it is being set. Move the routing inside callback to set the value and use it. Its also always good practice to include error callback in HTTP requests. This should work:
login(event: any) {
this.userService.getLogIn(this.email,this.password).subscribe(
data => {
this.adminFlag = data;
if (data) {
this.router.navigate("../../home");
}
},
error => {
console.error('getLogIn failed');
// handle error...
}
);
}
When you are executing:
this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
it means that you expect DATA to be a boolean. It's an observable boolean instead. To get the real boolean, use the pipe function, eg:
getLogIn(email:string,password:string):boolean{
let params = new HttpParams().set("userEmail",email).set("userPassword", password);
return this.http
.get<boolean>("http://localhost:8080/user/login",{params: params})
.pipe(map(data => data);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.