我正在对我的服务器进行api调用。这是组件代码
formData(username:string, password:string) {
if (username == "" || password == "") {
this.message = "Fields are empty";
} else {
this.loginservice.login(username,password).subscribe(heroes => this.serverRes = heroes);
}
}这是服务代码
login(username:string,password:string): Observable<any> {
console.log('loginService','called');
return of(this.http.post<any>(this.configUrl,
{
"username": username,
"password": password,
}));
}我不知道为什么它要进行两次api调用。第一个api请求没有request body,第二个api请求有request body。
发布于 2019-01-10 22:49:24
也许change Observable to Promise可以解决你在评论中描述的问题和错误:
谢谢..这是工作fine..but另一个问题。我在点击按钮时调用表单数据函数。当我点击按钮时,api调用正在进行,但服务中的登录函数返回空响应。如果我再次点击它,那么唯一的反应是coming..can,你帮我解决这个问题
login(username:string, password:string): Promise<any> {
console.log('loginService','called');
return new Promise((resolve, reject) => {
this.http.post<any>(this.configUrl,
{
"username": username,
"password": password,
})
.subscribe((res: any) => {
resolve(res);
},(error: HttpErrorResponse) => {
reject(error);
}
}
}
formData(username:string, password:string) {
if (username == "" || password == "") {
this.message = "Fields are empty";
} else {
this.loginservice.login(username,password)
.then((heroes: any) => {
this.serverRes = heroes
}
.catch(err: HttpErrorResponse) => {
//do something with error
}
}
}发布于 2019-01-10 22:55:32
为什么返回post函数的of?不要这样做,相反,只要返回帖子即可。
login(username:string,password:string): Observable<any> {
console.log('loginService','called');
return this.http.post<any>(this.configUrl,
{
"username": username,
"password": password,
});
}https://stackoverflow.com/questions/54122558
复制相似问题