无法存储POST方法的响应 [英] Unable to store the response of a POST method
问题描述
我能够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屋!