首页 > 解决方案 > 无法存储 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);
  }

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

标签: angularhttpclient

解决方案


您应该只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如此。


推荐阅读