I've been looking at component interactions and passing values from one component to a service, but couldn't find something clear enough.
The premise is simple, I have a variable / value that's coming from an API, and I need that variable to be passed to a service component (which holds the GET request and URL where I need the value).
I was thinking of using EventEmitter, to emit my variable, but then the service doesn't have an HTML to subscribe to it.
Here are some code snippets:
app.component.ts
private data: any[] = [];
ngOnInit(): void {
this.apiService.getData().subscribe(response => {
this.data = response.data;
console.log(this.data.id);
});
}
api.service.ts
@Injectable({
providedIn: 'root',
})
export class PromptApiService {
private readonly apiUrl = 'MY_API_URL;
/*I need the id variable from component to access here*/
constructor(
private http: HttpClient,
) {}
getData(): Observable<> {
return this.http.get<>(
`${this.apiUrl}/mydata`,
);
}
}
I had to remove some of the code for privacy reasons, as this is for a work project, so apologies if the code is minimal.
What would the best aproach be to pass the variable from component to service? Any suggestions would be greatly appreciated.
You can just move your data
variable to your service and then use that in your component(s) by making your service public
api.service.ts
@Injectable({
providedIn: 'root',
})
export class PromptApiService {
private readonly apiUrl = 'MY_API_URL';
public data: any[] = [];
constructor(private http: HttpClient) {}
getData(): Observable<> {
return this.http.get<>(`${this.apiUrl}/mydata`);
}
}
app.component.ts
export class AppComponent {
constructor(public promptApiService: PromptApiService)
ngOnInit(): void {
this.promptApiService.getData().subscribe(response => {
this.promptApiService.data = response.data;
});
}
}
app.component.html
<div *ngIf="promptApiService.data">
<p>{{ promptApiService.data.id }}</p>
</div>
Note: This assumes you are using the default change detection method and not OnPush