角度HTTP问题



问题是 - 我真的不知道如何正确使用 HTTP 服务在我的 angular 应用程序中获取和显示个人资料信息。这是我的用户配置文件组件:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UserService } from '../user.service';
import { userInfo} from '../shared/users_class';
import { Observable } from 'rxjs/Observable';
@Component({
 selector: 'app-user-profile',
 templateUrl: './user-profile.component.html',
 styleUrls: ['./user-profile.component.css']
})

export class UserProfileComponent implements OnInit {
 id:number;
 userInfo:userInfo;
 constructor(private router: ActivatedRoute, private userService:UserService) { }
 ngOnInit() {
 this.router.paramMap.subscribe(params=>{
  this.id = +params.get("id");
 });
  this.userService.getUserInfoFromDB(this.id).subscribe(data=>{
   console.log(data);
   this.userInfo = new userInfo(data.phone,
     data.marriage_status,
     data.city_birth, 
     data.current_city,
     data.sex
   );
  });
 }
}

我的用户-http-service函数:

getUserInfoFromDB(user_id) {
    return this.http.get('http://127.0.0.1:8000/user_info/'+ user_id)
                    .catch((error:any) =>{return Observable.throw(error);});;
}

我的 JSON - 从服务器响应:

{
"id": 4,
"phone": "123456789",
"marriage_status": 0,
"date_birth": "1997-01-23",
"city_birth": "someCity",
"current_city": "someCurrCity",
"sex": "M",
"user": 3
}

和这里的error_message

我的观点:

<div *ngIf="userInfo.date_birth">
  date_birth: {{userInfo.date_birth}}
</div><br>
<div *ngIf="userInfo.curr_city">
  curr_city: {{userInfo.curr_city}}
</div><br>
<div *ngIf="userInfo.phone">
  phone: {{userInfo.phone}}
</div><br>

这里的代码不是上帝的做法

getUserInfoFromDB(user_id) {
    return this.http.get('http://127.0.0.1:8000/user_info/'+ user_id)
                    .catch((error:any) =>{return Observable.throw(error);});;
}

在 catch 方法中,这个想法是处理错误而不是抛出一个新错误。

如果您使用的是 HttpCLient 类,那么数据已经转换为 json,如果 yoru 使用 HTTP 类来执行请求,那么您需要解析响应中提供的数据

如果您使用每个位置的可观察量并让视图处理可观察量,那就更好

userInfo: Observable<userInfo>
   this.userInfo = this.userService.getUserInfoFromDB(this.id).map(data=>{
return new userInfo(data.phone,
     data.marriage_status,
     data.city_birth, 
     data.current_city,
     data.sex
   );
  });
 }

您的视图将如下所示

<div *ngIf="(userInfo | async); let user">
  date_birth: {{user.date_birth}}
</div><br>
<div *ngIf="user.curr_city">
  curr_city: {{user.curr_city}}
</div><br>
<div *ngIf="user.phone">
  phone: {{user.phone}}
</div><br>

如何从路由中获取值

this.userInfo = this.router.paramMap.flatMap(params=>{
return this.userService.getUserInfoFromDB(params.get("id")).map(data=>{
return new userInfo(data.phone,
     data.marriage_status,
     data.city_birth, 
     data.current_city,
     data.sex
   );
  });
 });

最新更新