string interpolation not updating with value inside .subscribe()

Viewed 16

I have the following component:

@Component({
  selector: 'week-report-release-location',
  templateUrl: './week-report-release-location.component.html',
  styleUrls: ['./week-report-release-location.component.scss']
})
export class WeekReportReleaseLocationComponent implements OnInit, AfterViewInit {
  currentLocationForDisplay: string;

  constructor(
    private locationService: LocationService,
    private changeDetector: ChangeDetectorRef) {  }

  ngOnInit(): void {
    this.locationService.GetLocationsForUser().subscribe(locations => {
      this.currentLocationForDisplay = locations.reduce((previousValue, currentValue) => (previousValue ? previousValue+"," : "") + currentValue);;
      this.changeDetector.detectChanges();
    })

    //this.currentLocationForDisplay = "xxx";
  }

  ngAfterViewInit() {
     // ... code omitted
  }
}

Here is my html:

    <div fxLayout="column">
        <div class="card" style="margin: 1em;">
            <h4 class="card-title text-center" style="text-align: center; margin: 0.5em;">
                <strong translate>Wochenrapporte freigeben für {{ currentLocationForDisplay }}</strong>
            </h4>
        </div>

When I use the Line this.currentLocationForDisplay = "xxx" the value xxx will be displayed. But the value which is set inside the .subscribe() will never be shown.

I have tried the changeDetector as described here does not work either. What else can I do? I use Angular 10.2.0.

1 Answers

Take the reactive approach :


currentLocationForDisplay$ = this.locationService.GetLocationsForUser().pipe(
  startWith('xxxxxx'),
  switchMap(locations => locations.join(','))
);

in the HTML

<strong translate>
  Wochenrapporte freigeben für {{ currentLocationForDisplay$ | async }}
</strong>
Related