2017-04-05 4 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"); 
    } 
} 

私の予想は、上記のコードは一度に1人のユーザーを放出するということです。私は自分のコンポーネントでそのユーザーを購読して、怠惰なユーザーの読み込みエフェクトを生成することができます。私のコンポーネントのコードは次のとおりです。私は最終的に*ngForを使用してDOMに、このリストを反復処理しています

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

} 

はしかし私の驚きに観察可能で、配列そのものを見つけることができないとして.map上のエラーを与える:私は単に私のサービスからユーザーの配列を返す場合

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

、それが正常に動作します。私はここで何かmiisngですか?

答えて

0

矢印機能を使用します。

通常の機能でthisが変更されたため、this.usersが見つかりません。

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

それとも

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

実際のところ、私はすでにこれを実現して '.MAPに私のコードを変更する((I)=> this.users [I]);'私はそうではありません多くの使用された矢印機能が、私はこれがうまくいかなければならないと思います。一行の 'return'を中括弧で囲む必要はありません。しかし、これは私にエラーを与え、あなたのコードは正常に動作します。私の構文は間違っていますか? –

+0

私が答えで指定した両方の構文は同じです..あなたが '.map((i)=> return 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)を参照してください。 –

関連する問題