如何从 php API ( laravel 流明) 在 Angular 中获取数据数组
How to get an array of data from a php API ( laravel lumen) in Angular
我被卡住了,因为这是我第一次使用 Angular,我可能不了解一些基础知识。
我制作了一个 PHP API returns 来自 MySql 数据库的数据,我使用 HttpClient 在 angular 中获取它们。
对数据库的调用是
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 做 return
(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
您可以简单地为对象声明一个接口
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));
});
我被卡住了,因为这是我第一次使用 Angular,我可能不了解一些基础知识。
我制作了一个 PHP API returns 来自 MySql 数据库的数据,我使用 HttpClient 在 angular 中获取它们。
对数据库的调用是
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 做 return
(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
您可以简单地为对象声明一个接口
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));
});