[英]How to assign a value to variable inside subscription?
我有 Ionic 4 angular 项目,我需要在订阅内部阅读时分配值。 但是我不能那样做。 我知道有几个问题和答案与我的有关。 然而,他们都没有为我工作。 这是我的代码,到目前为止我已经尝试过。 任何评论,任何帮助都是appriciated。 非常感谢。`
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+"";
}
这是我尝试的另一个
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+"";
}
这是 page.ts
logForm(){
console.log(this.fineService.postLoginToServer(this.passwordUser, this.email));
}
他们两个都没有工作。 谢谢你。
因为它是调用 post 请求时的回调函数,并且因为 JS 是非阻塞的。 下面几行将在不等待 subscribe 函数调用的情况下执行。 因此你变得不确定。
尝试在 subscribe 函数内进行控制台日志记录,或者使服务函数作为异步流等待请求被处理。
据我了解,您正在尝试分配一个名为loggedChecker
的类属性。 这是你应该做的:
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) 运算符不会更改数据,但可用于执行您想要执行的操作。
更新:您应该更改 logForm 函数。
logForm(){
console.log(this.fineService.postLoginToServer(this.passwordUser, this.email));
}
应该
logForm(){
this.fineService.postLoginToServer(this.passwordUser, this.email).subscribe(data => {
console.log(data);
})
}
因为 HTTP 请求将返回一个 observable,当你订阅它时你会得到它的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.