Panda
Panda

Reputation: 415

How to pass the value of observable to const/let variable in angular

Here's the code:

HTML

 <nz-select
            class="header-selection"
            [ngModel]="currentRoom$ | async"
            (ngModelChange)="switchRoom($event)"
            name="sbu"
            [nzPlaceHolder]="'Select Room'"
            [nzDisabled]="(roomList$ | async).length === 1"
            >
            <nz-option
              *ngFor="let item of roomList$ | async"
              [nzLabel]="item.description"
              [nzValue]="item.code"
              [nzDisabled]="item.code === selectedRoom"
              >
            </nz-option>
          </nz-select>

TS

selectedRoom: any;
constructor() { this.switchRoom();
    ngOnInit() {

    this.currentRoom$.subscribe(room => { this.selectedRoom= room;  });
    }
    switchRoom(event) {
        this.currentRoom$.subscribe(room => { console.log(room)  });
        }

What I'm trying to do here is to pass the value of currentRoom observable. The problem is when I try to pass the value to variable it return null.

here's my code:

let data: any;
this.currentRoom$.subscribe(room => { data = room });
console.log(data);

but it doesn't display the value of currentRoom. If I try like this:

this.currentRoom$.subscribe(room => { data = room; console.log(data); });

then every time I click the function switchRoom() it loop like this.

1 'Room1' then when I switch to another room it will be like this

2 'Room3' then when I switch again going back to room 1 it will be like this

3 'Room1' it loops

Upvotes: 0

Views: 1140

Answers (1)

user13258211
user13258211

Reputation:

currentRoom$.subscribe() is asynchronous, which means that console.log(data) is executed before the assignment in the subscribe function happens, thus data is still undefined.

Replace

let data: any;
this.currentRoom$.subscribe(room => { data = room });
console.log(data);

with

let data: any;
this.currentRoom$.subscribe(room => { data = room; console.log(data); });

Upvotes: 1

Related Questions