首页 > 解决方案 > 需要帮助将返回的 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);

标签: phpangular

解决方案


如果我理解正确,它应该像将 http 请求中的值分配给实例变量一样简单

getBooks(): void {
  this.booksService.getBooks().subscribe( response => {
    this.books = response;
  }, 
  err => {
    console.log("error: " + err);
  });
}

推荐阅读