0

I want to use the HttpClient to make an API call and map the response to and class (not interface), I want that class to have certain methods with i can extend and later call in the HTML views.

I don't know why this isn't working as expected but it seems like it isn't possible for the HttpClient to map my json to classes.

The error that I get is: test is not a function

I'm trying to do this as followed:

User.ts

export class User {
  id: number;
  first_name: string;
  last_name: string;
  groups: Group[];

  test() {
    return 'test';
  }
}

Api.Service.ts

export class ApiService {

  private base_url: String = environment.api;

  constructor(private http: HttpClient) { }

  public me() {
    return this.http.get<User>(this.base_url + `user/me`);
  }
}

html:

<ng-container *ngIf="user | async; else loading; let user">
    {{user.test()}}
</ng-container>
<ng-template #loading>
    loading...
</ng-template>

controller:

export class UserController implements OnInit {

    user: Observable<User>;

    constructor(private api: ApiService) {}

    ngOnInit() {
        this.user = this.api.me()
    }
}
1

2 Answers 2

2

I ended up defining this in my class:

static fromJSON(data: any) {
    return Object.assign(new this, data);
}

Which will map the values correctly.

Sign up to request clarification or add additional context in comments.

Comments

1

You could do the following my frined:

export class User {
id: number;
first_name: string;
last_name: string;
groups: Group[];

test() {
  return 'test';
}

static fromJSON(json) {
    const user: User = new User();
    user.id = json.id;
    user.first_name = json.first_name;
    user.last_name = json.last_name;
    user.groups = [];

    json.groups.forEach(group => {
        user.groups.push(Group.fromJSON(group));
    });

    return user;
}

}

export class ApiService {

    private base_url: String = environment.api;

    constructor(private http: HttpClient) { }

    public me() {
      return this.http.get<User>(this.base_url + `user/me`).map(data => User.fromJSON(data.json()));
    }
}

You must add the same method 'fromJSON' to the 'Group' class in order to create a new Group object from the json.groups.

1 Comment

I'm using the new HttpClient from Angular which doesn't support .json() anymore, besides that I'm using http.get<User> so the response gets automatically mapped to the structure of my class. But the problem is that the HttpClient doesn't create a class (probably because of the JavaScript runtime).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.