如果不使用异步管道,则U应使用
我正在尝试将subscribe上的数据绑定到ngOninit,这是下面的页面profile.component.ts
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
}
}
这是下面显示的HTML模板页面profile.component.HTML
<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>
数据采用这种格式
[{
id: 9, addressID: 0, firstName: 'Dang', lastName: 'Kumar'
}]
我成功地获得了JSON中的数据,但是,
- 它在camelCase中接收,但我的模型是PascalCase
- 它不绑定
{{ obj.firstName }}
或[(ngModel)]="userDetails.FirstName"
上的数据,因为后者是Pascal的,而传入的JSON是Camel的- 即使我在Subscribe
userDetails.FirstName = "test"
中通过,它仍然不会绑定到[(ngModel)]="userDetails.FirstName"
- 它不绑定
在我使用的服务页面中。private currentUserId = new Subject<string>();
这是下面使用的代码
private currentUserId = new Subject<string>();
public get currentUsersIdValue() {
return this.currentUserId;
}
public set currentUsersIdValue(value) {
this.currentUserId = value;
}
现在的问题是new Subject<string>()
,我把它改成了new BehaviorSubject<string>('')
,效果很好。在订阅期间,subject
将不起作用,只有BehaviorSubject
起作用。
changeDetector.markForCheck()
将组件标记为脏组件。也不要使用嵌套订阅,我用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);