簡體   English   中英

為什么這張Angular材質表沒有渲染出來?

[英]Why is this Angular Material table not rendering?

我正在使用 Angular 9 和 Angular Material 開發一個聯系人應用程序。 列表組件應在表格行中為每個聯系人顯示一些信息和圖像。

在我的app.module.ts中,我導入了MatTableModule等。

app\services\contacts-list.service.ts我有:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

import { Contact } from '../models/Contact';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})

export class ContactsListService {

  contactsUrl = 'https://randomuser.me/api/?&results=20&inc=name,location,email,cell,picture';

  constructor(private http:HttpClient) { }

  getContcts():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

  getOneContact():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

}

app\components\list\list.component.ts我有:

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'city', 'country'];

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => { 
        this.contactsList = contactsList; console.log(contactsList);
        this.contactsTableData = new MatTableDataSource(contactsList);
      },
      error => { }
    );
  }
}

我上面的組件模板:

<div class="container">
    <h2 class="mat-display-1 page-title">{{pageTitle}}</h2>
    <div class="mat-elevation-z8">
        <mat-table [data-source]="contactsTableData">

            <ng-container matColumnDef="fullName">
                <mat-header-cell *matHeaderCellDef> Full Name </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.name.first}} {{element.name.last}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="photo">
                <mat-header-cell *matHeaderCellDef> Photo </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.picture.large}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="email">
                <mat-header-cell *matHeaderCellDef> Email address </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="city">
                <mat-header-cell *matHeaderCellDef> City </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.city}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="phone">
                <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.cell}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="country">
                <mat-header-cell *matHeaderCellDef> Country </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.country}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
    </div>
</div>

問題

我面臨的問題是只顯示表 header(列名),沒有數據,evan 認為組件中的console.log(contactsList)行正確顯示了聯系人列表:

[
  {
     "name":{
        "title":"Mr",
        "first":"Mair",
        "last":"da Cunha"
     },
     "location":{
        "street":{
           "number":1198,
           "name":"Rua Belo Horizonte "
        },
        "city":"Cachoeiro de Itapemirim",
        "state":"Tocantins",
        "country":"Brazil",
        "postcode":36034,
        "coordinates":{
           "latitude":"-78.1101",
           "longitude":"-171.0313"
        },
        "timezone":{
           "offset":"+5:00",
           "description":"Ekaterinburg, Islamabad, Karachi, Tashkent"
        }
     },
     "email":"mair.dacunha@example.com",
     "cell":"(66) 5998-0008",
     "picture":{
        "large":"https://randomuser.me/api/portraits/men/88.jpg",
        "medium":"https://randomuser.me/api/portraits/med/men/88.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/men/88.jpg"
     }
  }
]

什么東西少了?

在模板上, mat-table應該使用[dataSource]而不是[data-source] 那應該可以解決您的問題。

另外快速提示,您的響應不會返回ContactAM數組,而是返回一個 object 具有名為results的屬性,而該屬性又具有ContactAM數組的值。 因此,在您的service上,您進行HTTP GET call並將其鍵入ContactAM[]時,您實際上應該將其鍵入{ results: ContactAM[] }

以下是問題的解決方式,以防其他人可以使用這條信息:

app\components\list\list.component.ts文件中我有:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'phone', 'city', 'country'];

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => { 
        this.contactsList = contactsList;
        this.contactsTableData = new MatTableDataSource(contactsList);
        this.contactsTableData.paginator = this.paginator;
      },
      error => { }
    );
  }
}

在組件的模板中,我有:

<div class="container">
    <div class="mat-elevation-z8">
        <table mat-table [dataSource]="contactsTableData" class="w-100">
            <ng-container matColumnDef="fullName">
                <th mat-header-cell *matHeaderCellDef>Full Name</th>
                <td mat-cell *matCellDef="let element">{{element.name.first}} {{element.name.last}}</td>
            </ng-container>

            <ng-container matColumnDef="photo">
                <th mat-header-cell *matHeaderCellDef>Photo</th>
                <td mat-cell *matCellDef="let element">
                    <img src="{{element.picture.large}}" alt="{{element.name.first}} {{element.name.last}}" class="thumbnail rounded-circle">
                </td>
            </ng-container>

            <ng-container matColumnDef="email">
                <th mat-header-cell *matHeaderCellDef>Email address</th>
                <td mat-cell *matCellDef="let element">
                    <a href="mailto:{{element.email}}">{{element.email}}</a>
                </td>
            </ng-container>

            <ng-container matColumnDef="phone">
                <th mat-header-cell *matHeaderCellDef>Phone</th>
                <td mat-cell *matCellDef="let element">
                    <a href="tel:{{element.phone}}">{{element.cell}}</a>
                </td>
            </ng-container>

            <ng-container matColumnDef="city">
                <th mat-header-cell *matHeaderCellDef>City</th>
                <td mat-cell *matCellDef="let element">{{element.location.city}}</td>
            </ng-container>

            <ng-container matColumnDef="country">
                <th mat-header-cell *matHeaderCellDef>Country</th>
                <td mat-cell *matCellDef="let element">{{element.location.country}}</td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
        </table>
        <mat-paginator [pageSizeOptions]="[10, 20, 50]" [pageSize]="10" showFirstLastButtons></mat-paginator>
    </div>
</div>

我還有這個 styles,用於圖片:

.rounded-circle {
    border-radius: 50%!important;
}

.thumbnail {
    padding: 2px;
    line-height: 1;
    background-color: #fff;
    border: 1px solid #ddd;
    height: 40px;
    width: auto;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM