角度的,地图:地图给结果提供较晚订阅 [英] angular, map: map give result to subscribe late

查看:69
本文介绍了角度的,地图:地图给结果提供较晚订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用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);
      });

}

并以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.

错误截图.

推荐答案

进行了ngif测试,表明该用户不是未定义的,因此在加载该用户之前不会对其进行绑定:

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>

这篇关于角度的,地图:地图给结果提供较晚订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆