'async template bind from subscribe angular 13

I'm trying to bind data on subscribe on ngOninit, here is the page profile.component.ts below.

export class ProfileComponent implements OnInit {
  public userDetailsArr: UserDetails[] = [];
  private subscriptions: Subscription[] = [];

 async ngOnInit() {
    await this.userManagementService.currentUsersIdValue
      .subscribe(async (userId: number) => {
        const user = await this.userManagementService.getUsers(userId.toString())
          .subscribe(x => {
            this.userDetailsArr = x;
            console.log(this.userDetailsArr); // data shows here
          });
        this.subscriptions.push(user);
      });

  console.log(this.userDetailsArr); // data does not show here
}

}

Here is the HTML template page profile.component.html shown below.

<form>
    <div>
      <ng-container *ngIf="userDetailsArr as obj">
        {{ obj.firstName }} //does not show data
      </ng-container>
    </div>
    <input type="text" placeholder="First Name" [(ngModel)]="userDetails.FirstName" /> //does not bind model
</form>

Data comes in this format.

[{
  id: 9, addressID: 0, firstName: 'Dang', lastName: 'Kumar'
}]

I get data in JSON successfully but,

  1. It receives in camelCase but my model is of PascalCase
  2. It does not bind data on {{ obj.firstName }} or [(ngModel)]="userDetails.FirstName" as the latter is of Pascal I understand and incoming JSON is of Camel.
  3. Even though i pass within Subscribe userDetails.FirstName = "test" it still won't bind on [(ngModel)]="userDetails.FirstName".


Solution 1:[1]

In my service page I was using. private currentUserId = new Subject<string>(); Here is the code which was being used below.

  private currentUserId = new Subject<string>();
  public get currentUsersIdValue() {
    return this.currentUserId;
  }
  public set currentUsersIdValue(value) {
    this.currentUserId = value;
  }

Now the issue was the new Subject<string>() which I changed it to new BehaviorSubject<string>(''), this worked perfectly. During subscribe subject would not work only BehaviorSubject would.

Solution 2:[2]

U should mark component as dirty with changeDetector.markForCheck() if u don't use async pipe. Also dont use nested subscriptions, I fixed this with switchMap()

const userSubscription = this.userManagementService.currentUsersIdValue.pipe(
   switchMap((userId) => this.userManagementService.getUsers(userId.toString())),
).subscribe((users) => {
  this.userDetailsArr = users;
  this.changeDetector.markForCheck();
});
this.subscriptions.push(userSubscription);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 namco
Solution 2 ??????? ????????