2017-04-05 82 views
0

我是Angular2的新手,我有以下服务文件,它给了我一个错误。无法使用时间间隔从数组返回一个Observable

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

} 

我终于在迭代使用DOM这*ngFor名单。

但让我吃惊的可观测找不到阵列本身和.map给出一个错误:

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

如果我只是从我的服务回报用户阵列,它工作正常。所以我在这里做什么?

回答

0

使用箭头功能。

它找不到this.users,因为this在正常功能中发生了变化。

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

或者

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

作为事实上,我已认识到这一点,并改变了我的代码为'.MAP(第(i)=> this.users [I]);'我没有很多用过的箭头函数,但我认为这应该起作用。单行'return'不需要用大括号包裹。但是,这给了我错误,你的代码工作正常。我的语法错了吗? –

+0

我在答案中指定的两种语法都是等价的。如果给出.map((i)=> this this.users [i]),它将被视为'.map((i)=> {return return this.users [i];})'CHeck [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)。 –

相关问题