user9401912
user9401912

Reputation: 73

Angular observable service call giving undefined error

I have a service that makes an API call which retruns collection of valid users. below given is code snippet from service and component.

Error I am getting while mapping response to local variable defined in service is--> ValidUserCollection is undefined

Note: My call to service is successfull and I do get the response status as 200 and Ok : true. only issue seems to be when I am mapping the response to local variable defined in service.

Any advise as what I might be missing or doing wrong ?

Following is my service code for method defined in service.

 constructor(private http: Http){
        this.ValidUsersCollection = [];
    }

    GetAllUsers(): Observable<User[]>
    {
       return this.http.get('http://localhost:8055/api/user/GetAllUsers/', { headers: this.getHeaders() })
         .map(this.mapPersons)
    }

mapPersons(response:Response): User[]
    {
        return response.json().map(this.ValidUsersCollection)
     }

    private getHeaders() {
        let headers = new Headers();
        headers.append('Accept', 'application/json');  
        return headers;
    }


code from my component
    this.userSrv.GetAllUsers()
.subscribe(allusers => this.allUsersCollection = allusers);

Upvotes: 0

Views: 199

Answers (1)

Lia
Lia

Reputation: 11982

try something like this:

let ValidUsersCollection : User[] = [];
constructor(private http: Http){}

GetAllUsers(): Observable<User[]> {
       return this.http.get('http://localhost:8055/api/user/GetAllUsers/', { headers: this.getHeaders() })
         .map(res =>{
           return res.json().map(items => { this.ValidUsersCollection = items });
     });
}

Upvotes: 1

Related Questions