问题
I want to build a user page with Angular
.
In my service I am getting data by this code.
getUser(id: number): Observable<User> {
return this.http.get(`${this.baseUrl}/getUser.php?id=${id}`).pipe(
map((res) => {
this.user = res['data'];
return this.user;
}),
catchError(UsersService.handleError));
}
In component I am saving data into variable user. This is code.
user: User;
constructor(
private UsersSer: UsersService,
private ActiveRout: ActivatedRoute) {
}
ngOnInit() {
this.getUser();
}
getUser() {
const id = +this.ActiveRout.snapshot.paramMap.get('id');
this.UsersSer.getUser(id).subscribe(user => {
this.user = user;
console.log(this.user);
}, (err) => {
console.log(err);
});
}
And printing in html.
<div class="main-box clearfix">
<h2>{{user.name}}</h2>
<div class="profile-status">
<i class="fa fa-check-circle"></i> {{user.status}}
</div>
<img src="../../assets/images/{{user.image}}" alt="" class="profile-img img-responsive center-block">
<div class="profile-label">
<span class="label label-danger">{{user.role}}</span>
</div>
</div>
When i run code in browser i see that data comes too late.
I am new in stack overflow sorry if i do mistake.
Errors screenshot.
回答1:
Have an ngif testing that user isn't undefined so you're not binding to it before it's loaded:
<div class="main-box clearfix">
<div *ngIf="user != undefined">
<h2>{{user.name}}</h2>
<div class="profile-status">
<i class="fa fa-check-circle"></i> {{user.status}}
</div>
<img src="../../assets/images/{{user.image}}" alt="" class="profile-img img-responsive center-block">
<div class="profile-label">
<span class="label label-danger">{{user.role}}</span>
</div>
</div>
</div>
来源:https://stackoverflow.com/questions/53446194/angular-map-map-give-result-to-subscribe-late