I am trying to populate a dropdown by accessing an array property from the class which is wrapped inside an observable.
I have an interface like below :
export interface IApplicationConfigurationResponse
{
settings?: Settings[] ] undefined;
}
export class ApplicationConfigurationResponse
{
settings?: Settings[] ] undefined;
}
export class Settings
{
settingId!:number;
name!:string;
}
state-management.service.ts:
@Injectable
export class StateManagementService
{
private subjectConfigurations = new BehaviourSubject<ApplicationConfigurationResponse>(null);
getApplicationConfigurations(){
return this.subjectSettings.asObservable().pipe(filter(k) => k!=null);
}
set saveApplicationConfiguration(state: ApplicationConfigurationResponse)
{
this.subjectConfigurations.next(state);
}
}
master.component.ts:
@Component({
selector: 'app-master',
..
..
})
export class MasterComponent implements OnInit
{
constructor(private myService: MyService,
private stateService: StateManagementService) {}
ngOnInit():void {
this.myService.getApplicationConfigurationsFromBackend().subscribe((res) ==> {
this.stateService.saveApplicationConfiguration = res;
}
}
header.component.ts:
@Component({
selector: 'app-header',
..
..
})
export class HeaderComponent implements OnInit
{
applicationConfigurationResponse$ : Observable<ApplicationConfigurationResponse>();
constructor(private stateService: StateManagementService) {}
ngOnInit():void {
this.applicationConfigurationResponse$ = this.stateService.getApplicationConfigurations;
}
}
header.component.html:
<div>
<select class="dropdown">
<option *ngFor="let setting of applicationConfigurationResponse$.settings | async" [value] = "setting.settingId">
{{ setting.name }}
</option>
</select>
</div>
But I am getting error on below line:
I am not able to access the property which is wrapped inside an observable.
How can I access the Settings[]
from ApplicationConfigurationResponse
and populate a dropdown?
You need to access the observable, subscribe to it, then use the settings property using Async Pipe, or you can do something like this
export class HeaderComponent implements OnInit {
applicationConfigurationResponse$ :
Observable<ApplicationConfigurationResponse>();
constructor(private stateService: StateManagementService) {}
ngOnInit():void {
this.applicationConfigurationResponse$ =
this.stateService.getApplicationConfigurations;
}
get settings() {
return this.applicationConfigurationResponse$.pipe(map(res => res.settings));
}
}
and in html
<div>
<select class="dropdown">
<option *ngFor="let setting of settings | async" [value]="setting.settingId">
{{ setting.name }}
</option>
</select>
</div>