角度HTTP问题

时间:2018-03-20 11:38:24

标签: angular http

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

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 here

我的观点:

<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>

1 个答案:

答案 0 :(得分:0)

这里的代码不是神的实践

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类,那么如果yoru使用HTTP类来执行请求,则数据已经转换为json,那么你需要解析响应中的数据

如果你在每个地方使用observable并让视图处理可观察的

,那么

会更好

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
   );
  });
 });