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.
CodePudding user response:
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
CodePudding user response:
This kind of things can be a bit difficult when you are starting.
To pass a variable from a component to a service, you have a simple solution:
- Inside the service
api.service.ts
you can create the variable at the top and the setter:
@Injectable({
providedIn: 'root',
})
export class PromptApiService {
private myVariable:string; // THIS LINE
private readonly apiUrl = 'MY_API_URL';
constructor(
private http: HttpClient,
) {}
setMyVariable(myVariable:string):void { // THIS FUNCTION
this.myVariable=myVariable;
}
getData(): Observable<> {
...
}
}
- Inside
app.component.ts
you instance the service in the constructor and use the setter:
constructor( private apiSvc: PromptApiService ) {} // THIS LINE
ngOnInit(): void {
this.apiSvc.setMyVariable("HELLO"); // THIS LINE
}