【发布时间】:2019-06-04 05:05:51
【问题描述】:
我正在为我的网站构建登录/注册页面。如果我的用户模型中的电子邮件、用户名或密码字段留空,我有一个 django 后端会返回错误。在 Postman 中进行测试时,我能够成功返回错误。我的问题是在我部分成功的发布请求后捕获该数据并将其传递给我的 html(部分成功,因为我可以在我的后端注册一个新用户)。
这是我所拥有的:
api.service.ts
@Injectable({
providedIn: 'root'
})
export class ApiService {...
private formatErrors(error: any) {
return Observable.throw(error.json());
}
...
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(`${environment.api_url}${path}`, JSON.stringify(body), { headers: this.setHeaders()})
.pipe(
catchError(this.formatErrors),
map((res: Response) => res.json())
);
}
}
我认为以上所有内容都可以,除非我误解了 post 函数中的 pipe()/catchError() 方法。
我将它注入到另一个名为 user.service.ts 的服务中,其中我有一个使用上述 post 方法的尝试验证函数:
...
attemptAuth(type, credentials): Observable<User> {
let route = (type === 'login') ? '/login': '';
return this.apiService.post('/users' + route, {user: credentials})
.pipe(
map(data => {
this.setAuth(data.user);
return data;
})
);
}
...
该用户服务被导入我的 AuthComponent 并在此处使用:
...
submitForm() {
this.isSubmitting = true;
this.errors = new Errors();
let credentials = this.authForm.value;
this.userService.attemptAuth(this.authType, credentials)
.subscribe(
data => this.router.navigateByUrl('/'),
err => {
this.errors = err;
this.isSubmitting = false;
}
);
}
}
知道为什么在发出发布请求时我的前端没有获取后端提供的响应数据吗?我不相信我的错误发生在我的 html 或我用来实际喜欢错误的组件中。我想我会从上面开始。谢谢!
【问题讨论】:
-
你能尝试得到console.log()的响应吗,
this.userService.attemptAuth(this.authType, credentials) .subscribe( response => {console.log(response);});