简体   繁体   English

Angular 2回调

[英]Angular 2 callback

I created a service that gets the some data from the api this is the code 我创建了一个服务,从api获取一些数据,这就是代码

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. 我订阅了我想在ngOnInit中使用服务的组件,一切都运行良好。

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. 但现在我需要对数据使用过滤器,该过滤器应在ngInit完成获取数据后运行。 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. 好吧,我的问题是当我尝试在订阅代码之后放置函数我不断得到一个空数组,因为ngOnInit首先运行此函数然后获取数据。 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 并谢谢

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 注意 lvl将是未定义的,所以你要用你的逻辑来定义它

I haven't tried ( don't have access to angular2 at work :-( ), but you can have multiple statements in the lambda function in subscribe . 我没有尝试过(在工作中没有访问angular2 :-(),但你可以在subscribe中的lambda函数中有多个语句。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM