正如标题所说,我正在尝试从遵循单例模式的另一个类(评论)访问在一个类(帖子)中声明的方法。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] 删除。
我来说两句