title: How to show a loading spinner while waiting on an observable getting data from a service in Angular
body: <p>I have set up an observable service that helps me persist data, but I need a way to show a loading spinner while the data is waiting to come from the observable.</p>
  
  <p>My service:</p>
  
  <pre><code>imports [...]
  
  import { Observable, BehaviorSubject } from 'rxjs';
  
  @Injectable({
    providedIn: 'root'
  })
  export class OrganisationsService {
    private organisations$ = new BehaviorSubject&lt;Organisation[]&gt;([
      {
        [...]
      }
    ]);
  
    constructor(private http: HttpClient) {
      this.http
        .get(
          environment.apicall
        )
        .subscribe((data) =&gt; this.organisations$.next(data['organisations']));
    }
  
    getList(): Observable&lt;Organisation[]&gt; {
      return this.organisations$.asObservable();
    }
  </code></pre>
  
  <p>Here's my component:</p>
  
  <pre><code>    imports ...
  
      import UIkit from 'uikit';
      import { Observable } from 'rxjs';
  
      @Component({
        selector: 'app-organisationlist',
        templateUrl: './organisationlist.component.html',
        styleUrls: ['./organisationlist.component.css']
      })
      export class OrganisationlistComponent implements OnInit {
  
        public loading = true;
  
        public organisations$: Observable&lt;Organisation[]&gt;;
  
        constructor(public organisationsService: OrganisationsService) {}
  
        ngOnInit() {
          this.getData().then(() =&gt; {
            this.loading = false;
          });
        }
  
        async getData() {
          this.organisations$ = this.organisationsService.getList();
        }
  }
  </code></pre>
  
  <p>Here's my layout (uses Uikit):</p>
  
  <pre><code>  &lt;div *ngIf="loading" uk-spinner&gt;&lt;/div&gt;
    &lt;div&gt;
      &lt;ul class="uk-list"&gt;
        &lt;li *ngFor="let organisation of organisations$ | async"&gt;
          {{ organisation.name }}
        &lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
  </code></pre>
  
  <p>Obviously, the <code>getData</code> function, although declared async, is not actually async and returns immediately. So <code>this.loading</code> is 'false' OnInit, and therefore it doesn't show.</p>
  
  <p>There are plenty of answers around that show how this might work when the subscription happens in the component, but because this is shared data in a service, I can't find a way to wait on the data before setting <code>this.loading</code> to false.</p>
  
  <p>Many thanks.</p>