无法使用interval从数组返回Observable

时间:2017-04-05 07:01:26

标签: arrays angular rxjs observable angular2-observables

我是Angular2的新手,我有以下服务文件,这给我一个错误。

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

我的期望是上面的代码应该一次发出一个用户。我可以在我的组件中订阅该用户并产生延迟的用户加载效果。我的组件代码是:

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

}

我最终使用*ngFor在DOM上迭代此列表。

但令我惊讶的是,Observable无法找到数组本身并在.map上出错:

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

如果我只是从我的服务返回用户数组,它工作正常。我在这里有什么好看的吗?

1 个答案:

答案 0 :(得分:0)

使用箭头功能。

找不到this.usersthis在常规函数中已更改。

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

或者

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