php - 需要帮助将返回的 PHP 数据分配给 Angular 2 对象数组
问题描述
我不确定如何在我的角度类中使用我的 PHP 代码返回的数据。我希望能够使用我的书架组件来获取从后端返回的数据并创建一个 Book 数组。我从 PHP 接收数据很好,当我检查标题时我可以看到它返回。我只是对 Angular 不够熟悉,不知道如何将返回的数据分配给 Book 类型的数组。
图书界面
export interface Book {
id: number;
title: string;
rating: number;
}
书架组件(我想解析数据并将每个用作书)
import { Component, OnInit } from '@angular/core';
import { Book } from '../book';
import { BooksService } from '../books.service';
@Component({
selector: 'app-shelf',
templateUrl: './shelf.component.html',
styleUrls: ['./shelf.component.sass']
})
export class ShelfComponent implements OnInit {
books: Book[] = [];
constructor(private booksService: BooksService) {
}
ngOnInit() {
this.getBooks();
}
getBooks(): void {
this.booksService.getBooks().subscribe( response => {
console.log("success: " + response);
},
err => {
console.log("error: " + err);
});
}
}
图书服务(我在其中发送用作图书的数据的请求)
import { Injectable } from '@angular/core';
import { Book } from './book';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class BooksService {
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' })
};
constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> {
return this.http.post<Book[]>("http://localhost/Projects/index.php", this.httpOptions )
.pipe(map(response => response ));
}
}
PHP 代码
$books[] = [ 'id' => '1', 'title' => 'test', 'rating' => '5'];
$books[] = [ 'id' => '2', 'title' => 'test2', 'rating' => '6'];
echo json_encode($books);
解决方案
如果我理解正确,它应该像将 http 请求中的值分配给实例变量一样简单
getBooks(): void {
this.booksService.getBooks().subscribe( response => {
this.books = response;
},
err => {
console.log("error: " + err);
});
}
推荐阅读
- php - 如何通过将最后一行值和插入值相加来将值插入到 sql 数据库中
- mysql - SQL:使用登录/注销时间戳获取当前在线玩家数
- php - http post请求的php文件的正确路径是什么,以摆脱Angular中的404错误?
- ios - SWIFT:无法插入新的出口连接:在 Swift 语言中找不到名为 ViewController 的类
- java - volatile 变量没有给出预期的输出
- python - 用于打印 n 个素数集的 Python 脚本
- mysql - T-SQL 中 DATE 类型变量的 LIKE 运算符
- excel - 检查多个单元格范围是否相等
- azure-active-directory - Azure AD B2C 是否可以在线与 Dynamics Crm 配合使用?
- postgresql - 当我在 PostgreSQL 中使用 \d+ TABLE 命令时,输出换行