Search code examples
arraysangularrxjsobservableangular2-observables

Unable to return an Observable from array using interval


I am new to Angular2 and I have following service file which gives me an error.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/from';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/take';

@Injectable()
export class UserService {

    constructor(private _http: Http) { }
    private getUserUrl = 'data/data.json';
    private users = [
        { personal: { name: 'Saurabh', age: 24 }, role: 'Web Developer', hobby: 'Coding' },
        { personal: { name: 'Sunil', age: 24 }, role: 'Manual Tester', hobby: 'Drinking tea' },
        { personal: { name: 'Digvijay', age: 24 }, role: 'Onsite Tester', hobby: 'Gaming' },
        { personal: { name: 'Vinod', age: 24 }, role: 'C# Developer', hobby: 'Flirting' }
    ];

    getUsers() {
        return Observable.from(this.users) //tried with and without this `.from
            .interval(2000)
            .take(this.users.length) // end the observable after it pulses N times
            .map(function (i) { return this.users[i]; });
    }

    addUser(user: any) {
        this.users.push(user);
    }

    _errorHandler(error: Response) {
        return Observable.throw(error || "Server error");
    }
}

My expectation is that the above code should emit one user at a time. I could subscribe to that user in my component and produce a lazy user loading effect. My component code is :

export class UserComponent implements OnInit {

    users :any = [];

    constructor(private _userService: UserService, private _router : Router) { }

    ngOnInit() {
        //this.users = this._userService.getUsers();
        //code for real http data : Observable do not send data unless you subscribe to them
        this._userService.getUsers().subscribe(response => this.users.push(response));
    }

}

i am finally iterating this list on DOM using *ngFor.

However to my surprise the Observable can't find the array itself and gives an error on .map as :

TypeError: Cannot read property '0' of undefined
    at MapSubscriber.eval [as project] (http://localhost:8080/app/services/user.service.js:41:50)

If I simply return users array from my service, it works fine. So am I miisng something here?


Solution

  • Use arrow function.

    It cannot find this.users as this has changed in the regular function.

        .map((i) =>this.users[i]);
    

    Or

        .map((i)=> { return this.users[i]; });