Как получить данные как экземпляр класса из API - PullRequest
0 голосов
/ 05 августа 2020

Я новичок ie Angular, в настоящее время мне нужно получать данные из API, в EmployeesModels я установил метод расчета. С необработанными данными все работало, но данные из API имели ошибку в методе computeMonthlySalary. Я покажу свой код ниже, любую помощь или предложения. Большое спасибо!

EmployeesModels:

export class Employees implements IEmployees {
    constructor(public code: string, public name: string, public gender: string,
        public annualSalary: number, public dateOfBirth: string) {
    }
    computeMonthlySalary(annualSalary: number): number {
        return this.annualSalary / 12;
    }
}

Services

import {Employees} from '../Models/Employees';
import {HttpClient} from '@angular/common/http'
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class EmployeeServicesService {
  constructor(private _http: HttpClient) { }
  getEmployees(): Observable<Employees[]> {
    return this._http.get<Employees[]>('http://localhost:55416/api/employees');
  }    
}

EmployeeComponent

export class EmployeeComponent implements OnInit { 
    constructor(private readonly _employeeService: EmployeeServicesService){}
    employees: Employees[] = [];
    ngOnInit(){
        this._employeeService.getEmployees()
        .subscribe(employeesData => this.employees = employeesData);
    }
    
}

employeeList.component.template. html

<table>
    <thead>
        <tr>
            <th>Code</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Annual Salary</th>
            <th>Date of Birth</th>
            <th>Monthly Salary</th>
        </tr>
    </thead>
    <tbody>
        <ng-container *ngFor="let employee of employees;">
        <tr>
            <td>{{employee.code | uppercase}}</td>
            <td>{{employee.name |custompipe: employee.gender}}</td>
            <td>{{employee.gender}}</td>
            <td>{{employee.annualSalary| currency:'USD':true:'1.3-3'}}</td>
            <td>{{employee.dateOfBirth}}</td>
            <td>{{employee.computeMonthlySalary()|currency:'USD':true:'1.3-3'}}</td>
        </tr>
    </ng-container>
        <tr *ngIf="!employees || employees.length==0">
            <td colspan="6">
                No employees to display
            </td>
        </tr>
    </tbody>
</table>

И эта ошибка, когда я пытаюсь отобразить результат computeMonthlySalary

core.js:4197 ERROR TypeError: employee_r2.computeMonthlySalary is not a function

1 Ответ

1 голос
/ 05 августа 2020
this._http.get<Employees[]>('http://localhost:55416/api/employees')

Angular Служба HTTP не будет создавать для вас экземпляр нового класса, она предоставит вам только ответ, введенный в качестве параметра типа, который вы указали, это может сбивать с толку, но, по сути, вам не возвращаются экземпляры сотрудников. с помощью HttpClient он просто помогает с вводом текста.

Чтобы добиться того, что вам нужно, вам нужно создать экземпляр самостоятельно, я предлагаю вам сделать следующее

getEmployees(): Observable<Employees[]> {
  return this._http.get<IEmployees[]>('http://localhost:55416/api/employees').pipe(
    map((employees) => {
      return employees.map((employee) => {
         // Instantiate your classes
         return new Employee(employee.code, ....)
      });
    }),
  );
} 

Или вы можете использовать что-то вроде https://github.com/typestack/class-transformer

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...