0

I have a few components and services defined with functions that are called from respective components. Now I want to add a variable that can be set with a tag in the main app.component but can be accessed from anywhere. Can you suggest how to accomplish this?

    app.component.html
    <h1>{{title}}</h1>
        <nav>
        <a routerLink="/dashboard">Dashboard</a>
        <a routerLink="/comp1">Comp1</a>
        <a routerLink="/comp2">Comp2</a>
        <select class="form-control" id="selectedValue"
        [(ngModel)]="selectedValue">
          <option value="1">1</option>
          <option value="2">2</option>
        </select>
      </nav>
      <p>Selected value is {{selectedValue}}</p>
    <router-outlet></router-outlet>
    <app-messages></app-messages>

Something like this but I don't want the variable to be defined in app.component.ts but somewhere else, like in a "common/shared" service.

Then I'd use this variable in various services such as

 https://stackoverflow.com/posts/${selectedValue}
Alan Knap
  • 29
  • 6

1 Answers1

0

First of all, using global variables sometime means you don't have a proper code design, this might not be your case.

In any case, Günter's answer to this other post is probably what you are looking for.

If you think your problem could be solved in another way, feel free to add more information on what you are trying to achieve with your code.

Paul Evans
  • 434
  • 2
  • 13
  • I am trying to show a dropdown select box in the navbar that once selected/changed, will change a value that can then be accessed within across the whole app. That select will basically change credentials for various API calls. – Alan Knap Jul 03 '21 at 21:34
  • @AlanKnap If what you are trying to do is change credentials for various API calls, have a look at [interceptors](https://angular.io/api/common/http/HttpInterceptor). This might help you a lot. You might need to combine this with what I have previously shared. – Paul Evans Jul 03 '21 at 21:39