如何在 angular 中分配 api get 请求的响应数据

how to assign response data of api get request in angular

我正在向 api 端点发出获取请求,它发送一个 json 对象,我想要来自数据的课程数组 property.but 我不能,不知道我做错了什么,应该将 json 转换为对象 .... 错误是 属性 'key' 在类型 'Object' 上不存在。

这里的键应该等于“数据”,数据是 json 的 属性。

我的组件是

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators'
import { C } from './c.model';

@Component({
  selector: 'app-course',
  templateUrl: './course.component.html',
  styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
 courses :C[]=[];
  constructor(private http:HttpClient) { }

  ngOnInit(): void {
    this.fetchCourses();
  }

  private fetchCourses() {
    this.http.get('http://127.0.0.1:3000/api/courses/')
    .pipe(map( responseData =>{
      const coursesArray = [];
        for(const key in responseData){
          if(responseData.hasOwnProperty(key)){
             if(key === "data")
             {
               coursesArray.push(...(responseData.key.courses))
             }
          }
        }
        return coursesArray
      }))
    .subscribe(responsec=>{
      this.courses=responsec;
    })
  }

}

json 来自 api

{
    "status": "sucess",
    "numberOFResults": 5,
    "data": {
        "courses": [
            {
                "images": [],
                "tutors": [],
                "_id": "611c8899e135aa2c9cd39796",
                
          
            },
            {
                "images": [],
                "tutors": [],
                "_id": "611c8899e135aa2c9cd39794",
                "name": "arduno uno",
                
            },
            {
                "images": [],
                "tutors": [],
                "_id": "611c8899e135aa2c9cd39795",
                "name": "c/c++",
                "duration": 8,
                
            },
            {
                "images": [],
                "tutors": [],
                "_id": "611c8899e135aa2c9cd39798",
                "name": "ms office",
                "duration": 4,
               
            },
            {
                "images": [],
                "tutors": [],
                "_id": "611c8899e135aa2c9cd39797",
                "name": "web development",
                
            }
        ]
    }
}

key 这里是字符串类型,您正在使用访问 属性。 (点)。您需要使用方括号 [] 语法访问它。

改变这个

coursesArray.push(...(responseData.key.courses))

coursesArray.push(...((responseData as any)[key].courses))