简体   繁体   English

在父方法中调用订阅方法

[英]Call subscribe method inside the parent method

I have written a generic method like this: 我写了这样的通用方法:

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

Parent method (or calling) is like this: 父方法(或调用)是这样的:

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

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

I would like to remove the loading parameter from the genric method( getArticleById() ) and need to put that inside the parent method( myParentMethod() ) after resolving the subscription.Can you tell me how to do that? 我想从通用方法( getArticleById() )中删除加载参数,并需要在解决订阅后将其放入父方法( myParentMethod() )中。您能告诉我怎么做吗?

To handle the observable terminating at the higher level, you'll need to return an observable that the higher-level function can access. 要在更高级别处理可观察的终止,您需要返回一个更高水平的函数可以访问的可观察的终止。

Try writing it like this: 尝试这样写:

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 is a useful operator which finally是一个有用的运算符

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. 源可观察序列优雅地或异常地终止后,调用指定的操作。

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

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

However, this code is still structured a bit awkwardly. 但是,此代码的结构仍然有些尴尬。 I'd separate out the logic to get the observable from that to handle it, and write the code as follows: 我将逻辑从其中分离出来以进行处理,并编写如下代码:

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

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

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