Issue
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,
- It receives in camelCase but my model is of PascalCase
- 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. - Even though i pass within Subscribe
userDetails.FirstName = "test"
it still won't bind on[(ngModel)]="userDetails.FirstName"
.
Solution
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.
Answered By - namco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.