1
votes

I created a service that gets the some data from the api this is the code

getChallenges(): Observable<IChallenge[]> {
    if (this._challengeUrl != null) {
        return this.http.get(this._challengeUrl)
            .map((res:Response) => <IChallenge[]>res.json())
            .do(data => console.log('data: ' + JSON.stringify(data)))
            .catch(this.handleError);
    } else {
        //;
    }
}

and i subscribe inside the component where i want to use the service inside ngOnInit and everything is running my fine.

this._challengeService.getChallenges()
        .subscribe(challenges => this.challenges = challenges,
                    error => this.errorMessage = <any>error);

but now i need to use a filter on the data which should run after ngInit finishes getting the data. this is the filter:

filterByLvl(lvl){
    this.challenges.filter((obj)=> obj.level == lvl);
}

well my problem is when i try to put the function after the subscribe code i keep getting an empty array because the ngOnInit runs this function first and then gets the data. how can i inverse this? i need to get the data and then run this function. so any ideas on how to do this? and thanks

2
But, where are you keeping this filtered data ? In this example you are throwing away the filtered data. - Jagannath
omg you are exactly right it was like 4 am and im trying to solve it while my brain was almost dead :). haha i feed so stupid - Vay

2 Answers

0
votes

I haven't tried ( don't have access to angular2 at work :-( ), but you can have multiple statements in the lambda function in subscribe.

this._challengeService.getChallenges()
        .subscribe(challenges =>   
                     { 
                       this.challenges = challenges; 
                       filterByLvl(expert_level); 
                     },
                    error => this.errorMessage = <any>error
                   );
0
votes

One method would be filter directly when it retrieves the data something like:

this._challengeService.getChallenges()
        .subscribe(challenges => this.challenges = challenges.filter((obj)=> obj.level == lvl),
                    error => this.errorMessage = <any>error);

NOTE The lvl will be undefined so you've to define it someway with your logic