如何使用Ionic和API在HTML组件中显示数据

时间:2019-02-09 10:57:19

标签: angular ionic-framework

我在控制台中获取数据,但在Ionic的HTML组件中未获取数据。如何在blog-list.page.ts中显示数据。当我运行console.log(books)时,我正在获取数据,但是当我在HTML组件中尝试该数据时却没有获取数据。

book-list.page.ts

import { Component, OnInit } from '@angular/core';
import{Book} from '../book';
import { first } from 'rxjs/operators';
import{UserService} from '../user.service';

@Component({
  selector: 'app-book-list',
  templateUrl: './book-list.page.html',
  styleUrls: ['./book-list.page.scss'],
})
export class BookListPage implements OnInit {
  books: Book[] = [];
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.getBook()
  }

  getBook(){
  this.userService.getBook().pipe(first()).subscribe(books => {
  books = books;
  console.log(books);
});
  }
}

blog-list.page.html

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>
      Book List
    </ion-title>
    <ion-buttons slot="end">
      <ion-button routerLink="/user-detail">
        <ion-icon name="add-circle"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-card>


    <ion-card-content>
      <ion-card-subtitle>Books:</ion-card-subtitle>
      <ul *ngFor="let book of books">

        <li>{{book.title}}</li>

      </ul>
      <ion-buttons slot="primary">
        <ion-button routerLink="/edit/">
          <ion-icon slot="icon-only" name="create"></ion-icon>
        </ion-button>
        <ion-button (click)="delete()">
          <ion-icon slot="icon-only" name="trash"></ion-icon>
        </ion-button>
      </ion-buttons>
    </ion-card-content>
  </ion-card>
</ion-content>

1 个答案:

答案 0 :(得分:1)

您实际上需要将数据分配给变量books

getBook(){
  this.userService.getBook().pipe(first()).subscribe(books => {
    this.books = books; // use "this"
    console.log(this.books); // now your data is in your array
  });
}