【发布时间】:2017-07-06 04:49:46
【问题描述】:
当我试图在 Angular js 中显示数据表时。它显示表中没有可用数据,但表中有 4 条记录。请看下面的截图。
这就是我所做的。
user.component.ts
import { Component, OnInit } from '@angular/core';
import { UserModel } from './user-model';
import { UserService } from './user.service';
declare var $ :any;
@Component({
selector: 'user-page',
template: require('./user.component.html'),
providers: [ UserService ]
})
export class UserComponent implements OnInit {
data: any;
errorMessage: string;
constructor(private userService:UserService){ }
ngOnInit() {
this.getUsers();
}
getUsers() {
this.userService.getUsers()
.subscribe(
users => {this.data = users;
$(function(){
$("#user-table").DataTable();
});
},
error => this.errorMessage = <any>error);
}
}
user.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { UserModel } from './user-model';
@Injectable()
export class UserService {
private usersUrl = 'http://localhost/larang/public/api/users';
constructor (private http: Http) {}
getUsers(): Observable<UserModel[]> {
return this.http.get(this.usersUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) { console.log(error);
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
user.component.html
<table id="user-table" class="table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Added On</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of data">
<td>{{item.name}}</td>
<td>{{item.email}}</td>
<td>{{item.added}}</td>
</tr>
</tbody>
</table>
this.data 看起来像这样
[
{"name":"John Doe","email":"john.doe@gmail.com","added":"2017-04-26"},
{"name":"Ramkishan","email":"Ramkishan@gmail.com","added":"2017-04-26"},
{"name":"Jason Bourne","email":"jason@gmail.com","added":"2017-04-26"},
{"name":"RK","email":"ramkishan.suthar@ranosys.com","added":"2017-04-26"}
]
我做错了什么请帮忙。这对像我这样的 Angular JS 新手非常有帮助。
【问题讨论】:
-
发布您的数据的样子
-
是 2 分钟 @Sajeetharan
-
我已经更新了问题
-
它在表格中显示了 4 行对吗?
-
是的@Sajeetharan,抱歉重播晚了
标签: angular typescript datatable