angular - 无法存储 POST 方法的响应
问题描述
我能够 console.log POST 方法的响应。但我想将此响应存储在一个变量中,以便在代码中进一步使用它。请帮忙。
post 方法调用发送一个对象作为响应。
student.ts(Student 是一个类,与从 post 请求中收到的对象相同。)
export class Student {
ID : number;
firstName : string;
}
component.ts(在提交表单时调用 submit 方法。this.student 给出未定义的输出)
public student : Student[];
onSubmit() {
this._studentService.addData(this.addStudentForm.value)
.subscribe( response => console.log("respnse", response),
);
console.log(this.student);
}
服务.ts
addData(studentData) : Observable<any> {
return this.http.post<any>(this._url, studentData);
}
当我尝试将响应存储到变量中时,我得到的输出是未定义的。如何将响应存储在变量中?
解决方案
您应该只this.student = response;
在订阅中添加:
this._studentService.addData(this.addStudentForm.value).subscribe( response => {
console.log("respnse", response);
this.student = response;
});
但是如果你想对你做一些事情,student
你应该在next
订阅的回调中这样做:
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
如此。
推荐阅读
- maven - Maven Asciidoctor 插件和外部图像目录
- java - Java - 为运行我的应用程序的每个用户确定公共路径
- python - 在 python 代码下格式化不正确
- python - 使用powershell执行的批处理文件在远程机器上启动python
- angular - Angular6更新查询参数没有路由
- equation - 如何求解两个多项式方程组?
- pyspark - 仅给出一个集群的高斯混合模型 (GMM)
- php - opencart admin 中要求的页面级权限
- javascript - Ext JS 2.3 - 显示字段中的先前值 - 就像浏览器自动填充选择但不同
- r - R - ggplot() - 如何在绘图轴上对级别进行分组以表示对比假设