2017-04-05 48 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)。 –