vishwas jadav
vishwas jadav

Reputation: 299

ERROR Error: Uncaught (in promise): TypeError: users is undefined

I have an error in this Component and that error is not caught by command prompt.

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) );
  }
}
I can't understand what the problem is because i have defined "users" in the class. The method is called from this service.

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

The data I am getting is :

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

Upvotes: 3

Views: 5693

Answers (2)

AVJT82
AVJT82

Reputation: 73367

You don't have a data property in your response, as we can see you are simply getting an array, so you should return that. So in your service method getusers, instead of...

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

do:

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

Sidenote, you might have the same problem with your getuser (?) just for future reference if you run into same problem there :)

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222692

Try assigning to array and then remove

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

Upvotes: 0

Related Questions