【问题标题】:My response from api is undefined on frontend我的 api 响应在前端未定义
【发布时间】:2019-11-01 04:28:39
【问题描述】:

我从我的数据库 mySql 以及“编辑”按钮中获得了项目列表。 当我单击编辑(按 id)时,我想查看由数据填充的所有字段。 但我只有在我的控制台:未定义 如果我通过邮递员测试了我的 api,它可以正常工作。

这是我获取列表的方式。

{
    const id = this.actRoute.snapshot.paramMap.get('id');

    this.studentApi.GetStudent(id).subscribe((res: any) => {
      console.log(res.data);
      this.subjectArray = res.data;
      console.log(this.subjectArray);
      this.studentForm = this.fb.group({
        id: [res.id, [Validators.required]],
        domain_id: [res.domain_id, [Validators.required]],
        source: [res.source, [Validators.required]],
        destination: [res.destination]
      });
    });
  }

还有我的 api.service.ts

GetStudent(id): Observable<any> {
    const API_URL = `${this.endpoint}/read-student/${id}`;
    return this.http.get(API_URL, { headers: this.headers })
      .pipe(
        map((res: Response) => {
          return res || {};
        }),
        catchError(this.errorMgmt)
      );
  }

还有我的路线

studentRoute.get('/read-student/:id', (request, response) => {
  const id = request.params.id;
  con.query('SELECT * FROM students WHERE id = ?', id, (error, result) => {
      if (error) throw error;
      response.send(result);
  });
});

'邮递员'有回应

[
    {
        "id": 5,
        "domain_id": 2,
        "source": "tester0700@test.pl",
        "destination": "testw@test.pl"
    }
]

【问题讨论】:

    标签: mysql node.js angular


    【解决方案1】:

    看起来响应是一个数组,包含一个对象。

    在这种情况下,不需要使用res.data,因为这意味着返回的可观察对象res 有一个名为data 的属性,并且您正在尝试访问该属性中的值。您可以简单地将res 分配给subjectArray 属性。我很确定res 会被定义。

    this.studentApi.GetStudent(id).subscribe((res: any) => {
      console.log(res);
      this.subjectArray = res;
      // handle the rest here.
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 2021-07-05
      • 2018-08-12
      • 1970-01-01
      • 2020-05-14
      • 2020-01-16
      相关资源
      最近更新 更多