无法存储POST方法的响应 [英] Unable to store the response of a POST method

查看:40
本文介绍了无法存储POST方法的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够console.log POST方法的响应. 但是我想将此响应存储在变量中,以在代码中进一步使用它. 请帮忙.

I am able to console.log the response of a POST method. But I want to store this response in a variable to use it further in the code. Please help.

post方法调用发送一个对象作为响应.

post method call sends an object as response.

student.ts(学生"是一个类,与从发帖请求中接收到的对象相同.)

student.ts (the Student is a class which is same as the object received from the post request.)

export class Student {
ID : number;
firstName : string;
}

component.ts(在提交表单时调用submit方法.this.student提供未定义的输出)

component.ts (on submit method is called on submitting a form. this.student gives output as undefined)

public student : Student[];

onSubmit() {
    this._studentService.addData(this.addStudentForm.value)
      .subscribe( response => console.log("respnse", response),
        );
    console.log(this.student);
  }

service.ts

service.ts

addData(studentData) : Observable<any> {
    return this.http.post<any>(this._url, studentData);
  }

当我尝试将响应存储到变量中时,我得到的输出未定义. 如何将响应存储在变量中?

When i try to store the response into a variable i am getting output as undefined. How can i store the response in a variable ?

推荐答案

您应该只在订阅中添加this.student = response;:

You should just add this.student = response; inside subscribe:

this._studentService.addData(this.addStudentForm.value).subscribe( response => {
    console.log("respnse", response);
    this.student = response;
});

但是,如果您想对student进行操作,则应在next订阅的回调中执行此操作:

But if you want do something with student you should do this inside next callback of subscribe:

this._studentService.addData(this.addStudentForm.value).subscribe( response => {
    console.log("respnse", response);
    this.student = response;
    console.log(this.student) <- THIS WILL WORK - STUDENT IS NOT UNDEFINED
    // HERE ARE YOUR METHODS WHICH ARE USING STUDENT
});

在订阅之后,此console.log仍将是未定义的,因为此代码将在订阅结束之前执行,因此student暂时为undefinded.

This console.log after subsrciption still will be undefined, because this code will be executed BEFORE subscription is ended, so student is undefinded for this moment.

这篇关于无法存储POST方法的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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