我正在执行注册操作,当用户成功注册后在后端,我返回他的ID,例如“ 105”,并且当注册失败(用户已经存在)时,我返回“ USER_EXISTS”。我检查了邮递员的要求,回复的正文正确。
在两种情况下,我都返回“纯文本”。
但是,我无法找到如何通过返回的Observable对象获取响应的正文。
在register.component.ts中:
userExists = "";
onSubmit() {
const newUser : RegisterUser = { email: this.register.email,
password: this.register.password,
firstName: this.register.firstName,
lastName: this.register.lastName,
phoneNumber: this.register.phoneNumber}
this.registerService.addUser(newUser)
.subscribe(response => (this.userExists = response)); //The purpose of this line is to get the body of the text/plain response and assign it into the this.userExists string
}
在RegisterService.service.ts
addUser (registerUser) {
return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions);
}
答案 0 :(得分:2)
默认情况下,角度6产生 JSON 响应 如果您想要文本/纯文本,则应将 responseType 设置为“文本”
addUser (registerUser) {
return this.http.post(this.apiRoot + "User/add", {responseType: 'text'});
}
尝试将其附加到 httpOptions
答案 1 :(得分:1)
在RegisterService.service.ts中,添加地图并将响应转换为文本,如下所示:
addUser(registerUser){
return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions).map(res => res.text());
}