Angular6 - 读取 text/plain 的响应主体
Angular6 - Read response body of text/plain
我正在执行注册操作,当用户成功注册时,我会在后台执行 return 他的 ID,例如“105”并且当注册失败时(用户已经存在)我return"USER_EXISTS"。我已经检查了 Postman 上的请求,响应正文是正确的。
在这两种情况下,我 return "plain/text".
但是,我无法找到如何通过我获得的 Observable 对象获得响应的主体 return。
在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);
}
在RegisterService.service.ts中,添加地图并将响应转换为文本,如下所示:
添加用户(注册用户){
return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions).map(res => res.text());
}
默认angular 6 产生JSON响应
如果你想要 text/plain 你应该设置 responseType 为 'text'
addUser (registerUser) {
return this.http.post(this.apiRoot + "User/add", {responseType: 'text'});
}
尝试将其附加到 httpOptions
检查一下text/plain
我正在执行注册操作,当用户成功注册时,我会在后台执行 return 他的 ID,例如“105”并且当注册失败时(用户已经存在)我return"USER_EXISTS"。我已经检查了 Postman 上的请求,响应正文是正确的。
在这两种情况下,我 return "plain/text".
但是,我无法找到如何通过我获得的 Observable 对象获得响应的主体 return。
在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);
}
在RegisterService.service.ts中,添加地图并将响应转换为文本,如下所示:
添加用户(注册用户){
return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions).map(res => res.text());
}
默认angular 6 产生JSON响应 如果你想要 text/plain 你应该设置 responseType 为 'text'
addUser (registerUser) {
return this.http.post(this.apiRoot + "User/add", {responseType: 'text'});
}
尝试将其附加到 httpOptions
检查一下text/plain