我[ngx-datatable]
用来显示数据库中的一些数据。所以为此我制作了我的组件(这里我使用酒店作为组件)。所有酒店在数据表中都显示良好,但酒店名称的排序根本不起作用。当我点击酒店名称标题时,它会将表格显示为空白。
我从这里举了例子
所以现在 hotel.component.ts 看起来像这样
import { Component, OnInit } from '@angular/core';
import { HotelService } from '../hotel.service';
import { HttpClient } from '@angular/common/http';
import { Hotel } from './hotel';
import { Router} from '@angular/router';
import { ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-hotel',
templateUrl: './hotel.component.html',
styleUrls: ['./hotel.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HotelComponent implements OnInit {
hotels: Hotel[] = [];
loading: boolean = false;
rows = [];
columns = [
{ name: 'hotelname', sortable: true },
{ name: 'Action', sortable: false },
];
constructor(
public hotelService: HotelService,
private router: Router
) { }
ngOnInit() {
this.getAll();
}
getAll() {
this.hotelService.getHotels().subscribe(res => {
this.rows = res as Hotel[];
}, err => {
console.log(err);
});
}
onSort(event) {
// event was triggered, start sort sequence
this.loading = true;
setTimeout(() => {
const rows = [this.rows];
console.log(rows);
// this is only for demo purposes, normally
// your server would return the result for
// you and you would just set the rows prop
const sort = event.sorts[0];
rows.sort((a, b) => {
return a[sort.prop].localeCompare(b[sort.prop]) * (sort.dir === 'desc' ? -1 : 1);
});
this.rows = rows;
this.loading = false;
}, 1000);
}
}
hotel.component.html 看起来像这样
<div class="main-content">
<div class="container-fluid">
<div class="row">
<div>
<ngx-datatable
class="material striped"
[rows]="rows"
[columns]="columns"
[columnMode]="'force'"
[headerHeight]="40"
[footerHeight]="50"
[rowHeight]="'auto'"
[externalSorting]="true"
[loadingIndicator]="loading"
(sort)="onSort($event)">
</ngx-datatable>
</div>
</div>
</div>
</div>
和 hotel.service.ts 看起来像这样
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from "@angular/common/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
const domain = 'http://localhost:8080';
@Injectable()
export class HotelService {
headers = new Headers({ 'Content-Type': 'application/json' });
constructor(private http: Http) { }
getHotels(){
return this.http.get( domain + '/api/hotel', {headers: this.headers}).map(res => res.json() );
}
}