'Unable to call a method that is declared in one class from another singleton class
As the title says I'm trying to access a method that is declared in one class (Post) from another class (Comments) which is following a singleton pattern. Post class is a service class which has some methods to make API calls. So I need to have access to them from inside Comments class so that I can make API calls.
This is how a simplied version of Post class looks like right now:
@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}`);
}
}
This is how the Comments class look like:
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 );
});
}
}
How can I go about accessing it?
=========UPDATE=======
Creating an instance of Comment class in another class called ClassC.
const instance - Comments.createInstance();
instance.getComments( id );
Solution 1:[1]
Use a new service to save your comment object data let say We have a service named 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;
}
}
You should init PostService on your Comments Constructor
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
