I have this service:
Login (body): Observable<Login[]> {
//let bodyString = JSON.stringify(body); // Stringify payload
var bodyString = 'email='+body.email +'&password='+body.password;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post('/logiranje', bodyString, options) // ...using post request
.map(response => {return response}) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error' )); //...errors if any
}
I have component:
submitLogin(values){
var current = this;
// Variable to hold a reference of addComment/updateComment
let loginOperation:Observable<any>;
loginOperation = this.loginService.Login(values);
loginOperation.subscribe(
(response) => { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function(){
current.router.navigate(['/home']);
console.log("the subscription is completed");
}
);
}
What i want is to check :
if(response.isLoggedIn){
current.router.navigate(['/home']);
}
But i dont know how to pass value from service to component? Any suggestion how can i do that?
It seems that your you expect your response to be a JSON. You should then map it as below :
return this.http.post('/logiranje', bodyString, options)
.map(response => { response.json() })
.catch((error:any) => Observable.throw(error.json().error || 'Server error' ));
Since you already injected your service in your component you'll just have to assign the response to a variable :
data : any;
constructor(private loginService : LoginService) {}
myFunction(body){
this.loginService.Login(body).subscribe(
res => { this.data = res },
err => { console.log(err) }
);
}
Then you can use your data
variable
if(this.data.isLoggedIn){
current.router.navigate(['/home']);
}
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.