在父方法中调用subscribe方法

时间:2017-06-28 02:55:32

标签: javascript angular typescript rxjs observable

我写了一个像这样的通用方法:

getArticleById(loading: Loading): void {
    this.articleService.getArticleById(this.data.definition.id)
      .map((res: any) => res.json())
      .subscribe((res: any) => {
        if (res.definition.is_purchased) {
          //more code
          } else {
            //more code
          }
          loading.dismiss();
        } else {
           loading.dismiss();
        }
      }, () => { loading.dismiss(); });
  }

父方法(或调用)是这样的:

 myParentMethod(){
     const loading = this.loader.create({
      content: 'loading...'
    });
    loading.present();

    this.getArticleById(loading);//can I call the `loading.dismiss()` here. 
    }

我想从genric方法(getArticleById())中删除loading参数,并在解析订阅后需要将其放在父方法(myParentMethod())中。你能告诉我怎么做那?

1 个答案:

答案 0 :(得分:1)

要处理更高级别的可观察终止,您需要返回更高级别函数可以访问的observable。

尝试这样写:

getArticleById(loading: Loading) {
    const articles$ = this.articleService.getArticleById(this.data.definition.id)
      .map((res: any) => res.json());

    article$.subscribe((res: any) => {
        if (res.definition.is_purchased) {
          //more code
          } else {
            //more code
          }
    });

    return article$;  
}

finally是一个有用的运算符

  

在源可观察序列正常或异常终止后调用指定的操作。

myParentMethod(){
    const loading = this.loader.create({
      content: 'loading...'
    });
    loading.present();

    this.getArticleById().finally(() => loading.dismiss());
}

然而,这段代码仍然有点笨拙。我将逻辑分离出来以获得可观察的逻辑来处理它,并按如下方式编写代码:

getArticleById(): Observable<Article> {
    return this.articleService.getArticleById(this.data.definition.id)
      .map(res => res.json());
}

handleArticle(article) {
    if (article.definition.is_purchased) {
      //more code
    } else {
        //more code
    }
}

myParentMethod(){
    const loading = this.loader.create({
      content: 'loading...'
    });
    const article$ = this.getArticleById();

    loading.present();

    article$
      .finally(() => loading.dismiss())
      .subscribe(article => this.handleArticle(article));
}