我有Ionic 4角项目,我需要在阅读内部订阅时分配值。但是我做不到。我知道有几个与我有关的问答。但是他们都没有为我工作。这是我的代码,到目前为止我已经尝试过了。任何意见,任何帮助都适用。非常感谢。`
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+"";
}
这是页面。
logForm(){
console.log(this.fineService.postLoginToServer(this.passwordUser, this.email));
}
这两个都不起作用。谢谢。
答案 0 :(得分:2)
由于它是调用发布请求时的回调函数,并且由于JS是非阻塞的。下面的行将被删除,而无需等待订阅函数调用。因此您变得不确定。
尝试在订阅功能内进行控制台日志记录,或将服务功能设为异步,以使您的流等待请求被处理。
答案 1 :(得分:1)
据我了解,您正在尝试分配一个名为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(从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请求将返回一个可观察的对象,并且您在订阅它时将获得其值。