0

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.

3
  • 1
    Does this answer your question? Angular passing a variable from a component to a service Commented Feb 1, 2023 at 12:01
  • I think it sort of does answer my question, but same as the solution before, the variable I set in the service.ts file gets an IDE error that it's declared but never read. Commented Feb 1, 2023 at 12:28
  • 1
    That is not an error, that is warning message, also you need to assign the variably into the method itself. Commented Feb 1, 2023 at 12:34

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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:

  1. 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<> {
    ...
  }
}
  1. 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
}

1 Comment

This looks pretty straight forward, however I'm getting an error in the IDE that the variable is declared but never read - in the service.ts file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.