【问题标题】:How to get an array of data from a php API ( laravel lumen) in Angular如何从 Angular 中的 php API(laravel 流明)获取数据数组
【发布时间】:2020-06-23 12:33:17
【问题描述】:

我被困住了,因为这是我第一次使用 Angular,我可能还没有理解一些基础知识。

我制作了一个 PHP API,它从 MySql 数据库返回数据,并使用 HttpClient 以角度获取它们。

对数据库的调用是

    public function showOneCoursBy($id){
        $results = DB::select("select * from cours where id_cours = ".$id);
        return $results;
    }

访问我得到的 API 页面

[{"id_cours":1,"id_exercice":1,"titre":"XXX","description":"XXX","contenu":"XXX","mediaPath":"XXX","dateDebut":"0000-00-00","dateFin":"0000-00-00"}]

看来是对的。

在 Angular 中,我使用

  constructor(
    private firestore: AngularFirestore,
    private http: HttpClient,
    public db: AngularFirestore
  ) {
    this.http.get('http://localhost:3000/cours/').
    toPromise().then(data => {
      console.log(Object.keys(data).map(key => ({type: key, value: data[key]})));
      }
    );
  }

在服务中, console.log 确实返回

(2) […]
​
0: {…}
​​
type: "0"
​​
value: Object { id_cours: 1, id_exercice: 1, titre: "Premier Cours", … }
​​
<prototype>: Object { … }
​
1: {…}
​​
type: "1"
​​
value: Object { id_cours: 2, id_exercice: 2, titre: "Cours n°2", … }
​​
<prototype>: Object { … }
​
length: 2
​
<prototype>: [

但是我怎样才能只将其中一个元素作为数组?还是只访问一个属性?

提前致谢! :D

【问题讨论】:

  • 你的意思是这样的:Object.keys(data).map(key =&gt; ({type: key, value: data[key]}))[0]

标签: php angular api httpclient lumen


【解决方案1】:

您可以简单地为对象声明一个接口

export interface Exercice { 
  id_cours: number;
  id_exercice: number;
  titre: string;
  description: string;
  contenu: string;
  mediaPath: string;
  dateDebut: string;
  dateFin: string
}

您可以通过将您的响应输入为“练习”来访问数据

 this.http.get('http://localhost:3000/cours/')
   .pipe(take(1))
   .subscrible((response: Exercice[]) => {
     response.forEach(exercice => console.log(exercice.titre));
   });

【讨论】:

  • 感谢您的响应 =) 似乎有效,但我无法让它显示它,因为它正在执行诸如 ``this.allExercice = response ``` 给我一个“this .allExercice 未定义" 或 `` response.forEach(exercice => this.allExercice.push(exercice)); ``` 给我同样的错误......返回响应给我一个“类型'void'不可分配给类型'Exercice []'。”
  • 你是如何声明 allExercice 数组的?你初始化了吗?通过声明例如:私有 allExercice: Exercice[] = [];
猜你喜欢
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 2019-10-06
  • 2019-03-22
相关资源
最近更新 更多