Angular6-读取文本/纯文本的响应主体 [英] Angular6 - Read response body of text/plain

查看:278
本文介绍了Angular6-读取文本/纯文本的响应主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行注册操作,当用户成功注册后在后端,我返回他的ID,例如"105",当注册失败(用户已经存在)时,我返回"USER_EXISTS".我已经检查了邮递员的要求,并且回复的内容正确无误.
在这两种情况下,我都返回纯文本/文本".

I am performing a sign-up action and in my backend when the user successfully registers I return his id e.g. "105" and when the register fails (user already exists) I return "USER_EXISTS". I have checked the request on Postman and the body of the response is correct.
In both cases, I return "plain/text".

但是,我无法找到如何通过返回的Observable对象获取响应的正文.

However, I am not able to find how to get the body of the response through the Observable object that I get return.

在register.component.ts中:

In 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

In RegisterService.service.ts

addUser (registerUser) {

    return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions);
}

推荐答案

默认情况下,角度6产生 JSON 响应 如果您想要文本/纯文本,则应将 responseType 设置为文本"

By default angular 6 produce JSON reponse if you want text/plain you should set responseType as 'text'

 addUser (registerUser) {
    return this.http.post(this.apiRoot + "User/add", {responseType: 'text'});
 }

尝试将其附加到 httpOptions

检查 文本/纯文本

这篇关于Angular6-读取文本/纯文本的响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆