错误 错误: 未捕获 (在承诺中): 类型错误: 用户未定义



我在这个组件中有一个错误,命令提示符没有捕获该错误。

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);
}
}

我得到的数据是:

[{"id":"1","fname":"Vishwas","lname":"Jadav","email":"vjadav@live.com","dpic":"2017-10-7--09-12-19.jpeg","phone":"7621823474","passw":"illj123","type":"2"}]

你的响应中没有data属性,因为我们可以看到你只是得到一个数组,所以你应该返回它。所以在你的服务方法getusers,而不是...

.then(response => response.json().data as User[])

做:

.then(response => response.json() as User[])

旁注,如果您的getuser(?)遇到相同的问题,如果您在那里遇到相同的问题,您可能会遇到相同的问题(?)以供将来参考:)

尝试分配给数组,然后删除

ngOnInit() : void{
    this.userservice.getusers().then(users => this.users = users;
     this.users =this.users.slice(1,5);       
  });

相关内容

最新更新