I have Ionic 4 angular project, I need to assign value while reading inside subscribe. However I could not do that. I know there are several Questions and Answers related to mine. However none of them is working for me. Here is the my code and I tried so far. Any comments, any help is appriciated. Thank you very much.`
public loggedChecker: any;
private lofff = new Subject<any>();
postLoginToServer (password, email) {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let postData = {
password: password,
mail: email
}
console.log("8888888888888888888888888888888");
this.http.post("http://localhost:8080/api/login", postData, { observe: 'response'} )
.pipe(map(data => this.loggedChecker =(data.body)));
console.log(this.loggedChecker,"0330303333333333"); //undefined
return this.loggedChecker+"";
}
And here is the another I try
postLoginToServer (password, email) {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let postData = {
password: password,
mail: email
}
this.http.post("http://localhost:8080/api/login", postData,{observe: 'response'})
.subscribe(data => {
this.loggedChecker =(data.body);
this.textToDisplay = (data.body);
this.lofff.next(data);
}, error => {
console.log(error);
});
console.log(this.lofff,"logged checker");
return this.loggedChecker+"";
}
Here is the page.ts
logForm(){
console.log(this.fineService.postLoginToServer(this.passwordUser, this.email));
}
Both of them are not working. Thank you.
From what I understand you are trying to assign a class property named loggedChecker
.
This is what you should do:
postLoginToServer (password, email) {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let postData = {
password: password,
mail: email
}
this.http.post("http://localhost:8080/api/login", postData,{observe: 'response'})
.pipe(tap(data => {
this.loggedChecker =(data.body);
this.textToDisplay = (data.body);
this.lofff.next(data);
}, error => {
console.log(error);
}));
}
tap(import from rxjs) operator will not change the data but can be used to do things like what you're trying to do.
UPDATE: You should change your logForm function.
logForm(){
console.log(this.fineService.postLoginToServer(this.passwordUser, this.email));
}
should be
logForm(){
this.fineService.postLoginToServer(this.passwordUser, this.email).subscribe(data => {
console.log(data);
})
}
because the HTTP request will return an observable and you will get its value when you subscribe to it.