无法从另一个单例类调用在一个类中声明的方法

正如标题所说,我正在尝试从遵循单例模式的另一个类(评论)访问在一个类(帖子)中声明的方法。Post 类是一个服务类,它具有一些进行 API 调用的方法。所以我需要从 Comments 类中访问它们,以便我可以进行 API 调用。

这是 Post 类的简化版本现在的样子:

@Injectable({
  providedIn: 'root'
})
class PostService extends AnotherService {

  constructor( auth: AuthService, http: HttpClient ) {
    super('string', auth, http);
  }

  getPost( id: string ) {
    return this.http.get(`posts/${id}`);
  }

}

这是 Comments 类的样子:

class Comments {

    private postService: PostService;
    private static instance;
 
    private constructor() {}

    static createInstance() {
        if ( !Comments.instance ) {
            Comments.instance = new Comments();
        }
        return Comments.instance;
    }

    getComments( id ) {

        // these does not even run
        this.postService.getPost( id )
            .then( post => {
                 console.log( post );
            })
            .catch( error => {
                 console.log( error );
            }); 

    }

}

我该如何访问它?

=========更新=======

在另一个名为 ClassC 的类中创建 Comment 类的实例。

const instance - Comments.createInstance();
instance.getComments( id );
兹雷利·马吉迪

如果您想并行发送两个 http 请求然后获取它们的值您应该使用 combineLatest rxjs 运算符。您的邮政服务将是这样的:

getPost(id: string) {
  $postDataHttpRequest = this.http.get(`posts/${id}`);
  $commentsDataHttpRequest = this.http.get(`posts/${id}/comments`);
  return combineLatest($postDataHttpRequest, $commentsDataHttpRequest)
}

///

这是 Comments 类的样子:

  private constructor(private postService: PostService) {

  }
      getComments() {
            this.postService.getPost( '1' )
              .subscribe( (posts,comments) => {
                console.log(posts);
                console.log(comments);
              },(error)=>{console.log(error)})
             
      }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何调用在另一个类中声明的方法(C ++)

调用在 python 中另一个类中声明的类

如何使用或调用在另一个类中声明的静态变量

从另一个方法调用在一个方法中声明的实例

使用在另一个类中调用的方法设置 edittext 文本

无法从另一个类调用接口方法

从Python 2.7中的另一个类方法调用一个类方法

在Ruby的另一个类中的一个类中调用方法

如何从另一个类中迅速调用另一个方法?

Repaint()方法在另一个类中调用

从UIButton中的另一个类调用方法

在PHP的另一个类中调用方法

从另一个类中的一个类调用方法

如何在另一个类中调用一个类的main()方法?

从另一个类中的一个类调用方法

如何使用在另一个类中声明的变量

无法在另一个类中调用类方法

无法覆盖另一个模块swift中在类扩展中声明的open方法

无法从 JAVA 中同一类的另一个方法调用方法

无法在同一类JS的另一个方法中调用方法

使用在另一个类的类方法中创建的变量

无法从同一类中的另一个方法调用一个方法

在同一个类的另一个方法中调用一个类的方法的对象

从另一个类调用类方法

Javascript:Phaser在另一个方法类中调用一个方法

一个类调用另一个类的方法(nstimer),该方法无法调用选择器

如何在没有调用对象的情况下使用在另一个类中定义的方法?

如何调用在按钮元素的另一个活动/类onClick()中定义的方法?

如何使用在主类中调用/设置的另一个类在类上设置值