首页 > 解决方案 > HTTPClient Angular

问题描述

我是 angular6 的新手,我以前做过很多 android 项目,并且我有 Spring 和 Hibernate 设置。这与 Android volley 配合得非常好。

现在我发现很难从 RestAPI 中提取数据,所以 REST api 数据是:

collection  {
  version   : "1.0"
  error : null
  **data    : {
      id    : 1
      name  : "Test"
      password  : "MTIzNDU="
      createdDate : null
      email : "s.puspharaj@gmail.com"
      userArea  : "coimbatore"
      fcmTokenId    : ""
      mobileNo  : 4545456456
      googleAuth    : "yes"
      appVersionCode    : null
      }**
      statusCode    : 200
      booleanStatus : null }

如何在 Angular6 中提取上述收集数据?我不确定如何像在 android 中那样在 Angular 中进行调试。如何以角度将其保存在用户模型中?

用户模型类:

export class User {
id: number;
name: String;
createdDate: Date;
email: String;
userArea: String;
fcmTokenId: String;
mobileNo: String;
googleAuth: String;
appVersionCode: String;
modifyDate: String;
serverTime: String;

get getid() {
    return this.id;
}

set setid(id: number) {
    this.id = id;
}

get getName() {
    return this.name;
}

set setName(name: String) {
    this.name = name;
}

收藏模型:

export class Collection {
public version: String;
public data: Object;
public error: CollectionError;
public statusCode: number;
public booleanStatus: boolean;

get getError() {
    return this.error;
}

/**
 * @param error the error to set
 */
set setError(error: CollectionError) {
    this.error = error;
}

/**
 * @return the version
 */
get getVersion() {
    return this.version;
}

/**
 * @param version the version to set
 */
set setVersion(version: String) {
    this.version = version;
}

/**
 * @return the data
 */
get getData() {
    return this.data;
}

/**
 * @param data the data to set
 */
set setData(data: Object) {
    this.data = data;
}

get getStatusCode() {
    return this.statusCode;
}

set setStatusCode(statusCode: number) {
    this.statusCode = statusCode;
}

get isBooleanStatus() {
    return this.booleanStatus;
}

set setBooleanStatus(booleanStatus: boolean) {
    this.booleanStatus = booleanStatus;
}

}

到目前为止,我尝试过的 HTTP 客户端是:

 constructor(private http: HttpClient) { }

 getUser(): Observable<Collection> {
   return this.http.get<Collection>('http://localhost:8080/tooveWeb/v1/user/1');
}

onClickLogin() {
this.data.getUser().subscribe((collection) => this.collection.user = 
collection.user);
console.log(this.collection);

}

如何提取数据并存储到模型类并呈现给 html?

请建议!

谢谢

标签: angularrest

解决方案


在您的subscriptiontogetuser()方法中,您可以将响应数据分配给类的user属性Collection

private collection : Collection = new Collection() // method 1

或者

Collection在你的组件中注入类

constructor(private collection : Collection) { }  // method 2

this.getUser.subscribe((coll)=> {      
     this.collection.user= coll.data
})

推荐阅读