angular, map: map give result to subscribe late

孤者浪人 提交于 2019-12-11 15:52:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!