我在此组件中出错,并且命令提示符未捕获该错误。
Dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { User } from './user.component';
import { UserService } from './user.service';
@Component({
selector : 'dashboard',
templateUrl : './views/dashboard-component.html',
styleUrls: ['./views/css/dashboard-component.css'],
providers: [UserService]
})
export class DashboardComponent {
users: User[] = [];
constructor(private userservice: UserService){}
ngOnInit() : void{
this.userservice.getusers().then(users => this.users = users.slice(1,5) );
}
}

user.service.ts
import { Injectable } from '@angular/core';
import { User } from './user.component';
import { USERS } from './mock-users';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class UserService {
private usersUrl = "http://localhost/user/src/app/userlist.php";
constructor(private http: Http) { }
getusers() : Promise<User[]>{
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json().data as User[])
.catch(this.handleError);
}
getuser(id: number): Promise<User> {
const url = '${this.usersUrl}/${id}';
return this.http.get(url)
.toPromise()
.then(response => response.json().data as User)
.catch(this.handleError);
}
private handleError(error : any): Promise<any> {
console.error('an error occured', error);
return Promise.reject(error.message || error);
}
}
&#13;
我得到的数据是:
[{"id":"1","fname":"Vishwas","lname":"Jadav","email":"vjadav@live.com","dpic":"2017-10-7--09-12-19.jpeg","phone":"7621823474","passw":"illj123","type":"2"}]
答案 0 :(得分:1)
你的回复中没有data
属性,因为我们可以看到你只是得到一个数组,所以你应该返回它。因此,在您的服务方法getusers
中,而不是......
.then(response => response.json().data as User[])
做的:
.then(response => response.json() as User[])
旁注,如果你遇到同样的问题,你的getuser
(?)可能会遇到同样的问题以供将来参考:)
答案 1 :(得分:0)
尝试分配给数组,然后删除
ngOnInit() : void{
this.userservice.getusers().then(users => this.users = users;
this.users =this.users.slice(1,5);
});