title: How to cancel / close a behavior subject in angular
body: <p>I have a component that is subscribed to a behavior subject in the <code>ngOnInit</code> life cycle. This component html uses <code>ngIf</code> to see if data is there before rendering the table.</p>
  
  <p>When I navigate away from the page, I am wanting to make sure that the next time I come back, the table isn't visible until that data is then fetched again. The only way I have been able to do this so far is by calling next on the subject and sending an empty string, which feels wrong..</p>
  
  <p><strong>Component:</strong> </p>
  
  <pre><code>mapMetaData: any;
  
  ngOnInit() {
  
      // Subscribe to our map data
      this._mapsService.uiMapMetaData
      .subscribe(
          results =&gt; {
              if (results) {
                  this.mapMetaData = results;
              }
          }
      );
  
  }
  
  /**
   * Implement onDestroy life cycle
   * 
   * @memberof ViewMapComponent
   */
  ngOnDestroy() {
      this._mapsService.updateMapMetaData('');
  }
  </code></pre>
  
  <p><strong>HTML:</strong></p>
  
  <pre><code>&lt;span *ngIf="mapMetaData"&gt;
      &lt;div class="page-header"&gt;
          &lt;h3 class="text-primary"&gt;{{ mapMetaData.TargetName }} &lt;small&gt;{{ mapMetaData.TargetDesc }}&lt;/small&gt;
              &lt;button type="button" class="btn btn-default btn-sm pull-right" role="button" (click)="backToMaps()"&gt;
                  &lt;i class="fa fa-arrow-left"&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;Back to Maps
              &lt;/button&gt;
          &lt;/h3&gt;
      &lt;/div&gt;
      &lt;app-map-versions [targetID]="targetID"&gt;&lt;/app-map-versions&gt;
      &lt;app-map-exceptions [targetID]="targetID"&gt;&lt;/app-map-exceptions&gt;
      &lt;app-map-rules&gt;&lt;/app-map-rules&gt;
  &lt;/span&gt;
  </code></pre>
  
  <p>The issue is, without sending the empty <code>next</code> to the behavior subject, <code>mapMetaData</code> still contains what it received from the previous <code>next</code> call, resulting in the table showing when I come back to it, containing old data, and then very quickly changing when new data is received.</p>
  
  <p>Is there a better way to handle this or am I doing it correctly?</p>