If you're just trying to make some post requests see the first section, if you actually need to call another component's methods see the second section.
I'm afraid you might be making a whole component just to make post requests - which is not necessary. You can just make a service for this.
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(private http: HttpClient) {}
post(): Observable<any> {
return this.http.post<any>('https://reqres.in/api/posts', {
title: 'Angular POST Request Example',
});
}
}
Then make the request in any component
export class SomeComponent {
constructor(private myService: MyService) {}
qwe() {
this.myService.post().subscribe((data) => {
console.log(data);
});
}
}
If you want other components to call this component's methods you can create a service for this component. You can put a Subject
inside of it, which this component can subscribe to, and other components can call next()
on.
@Injectable({
providedIn: 'root',
})
export class PostRequestService {
qweSubject = new Subject<void>();
}
In this component, we can subscribe to the subject so we know when other components want to call the method. Make sure to unsubscribe when the component is destroyed to prevent memory leaks - this is necessary because the service never gets destroyed, so the subject will not clean up its own subscriptions.
export class PostRequestComponent implements OnInit, OnDestroy {
postId: any;
qweSub = new Subscription();
constructor(
private http: HttpClient,
private prService: PostRequestService
) {}
ngOnInit(): void {
this.qweSub = this.prService.qweSubject.subscribe(() => this.qwe());
}
qwe() { ... }
ngOnDestroy() {
this.qweSub.unsubscribe();
}
}
And in other components, we inject the service and call next()
when we want to call the method.
export class SomeComponent {
constructor(private prService: PostRequestService) {}
qwe() {
this.prService.qweSubject.next();
}
}