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

时间:2017-10-27 10:49:37

标签: php angular

我在此组件中出错,并且命令提示符未捕获该错误。

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



 我无法理解问题是什么,因为我已经定义了#34;用户"在课堂里。 从该服务调用该方法。

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;
&#13;
&#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"}]

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