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

Unable to call a method that is declared in one class from another singleton class

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

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

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

}

评论 class 是这样的:

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 的 class 中创建 Comment class 的实例。

const instance - Comments.createInstance();
instance.getComments( id );

使用新服务保存您的评论对象数据 假设我们有一个名为 SharedDataService 的服务。

private _comments: Array<any> =[];// or array<IComment> (a defined interface from your part)
class SharedDataService(){}
get comments():Array<any>{
return this._comments}
set comments(value:Array<any>){
this._comments = value;

}

}

您应该在评论构造函数中初始化 PostService

    private constructor(private postService: PostService,private sharedDataService :SharedDataService) {

}

    getComments() {

        // these does not even run
        this.postService.getPost( '1' )
            .then( post => {
this.sharedDataService.comments = post // if You get an array of comments here
                 console.log( post );
console.log(this.comments)// getter function its new value has been set
            })
            .catch( error => {
                 console.log( error );
            }); 

get comments(){

this.sharedDataService.comments

}

    }

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

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

///

评论 class 是这样的:

  private constructor(private postService: PostService) {

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