Search code examples
angularweb-servicestypescriptdata-bindingangular-services

need to get data from web service using Angular 4 service


I created a service to help me pull details from a web service by sending a specific ID to the back-end then fetching data regarding the selected ID, I created a function to call the service, now i want just to know what is missing in my code.

My service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpParams } from 
'@angular/common/http';
import { environment } from '../../environment/environment'
import { SchoolsModel } from '../models/school-model';

@Injectable()
export class GradesService {
constructor(public http: HttpClient) {
}

public getSchoolGrades(schoolId: number) {
const apiUrl: string = environment.apiBaseUrl + 
'/api/en/admin/grades/division';
let promise = new Promise((resolve, reject) => {
  return this.http.get(apiUrl, { params: new 
HttpParams().set("school_id", schoolId.toString()) })
    .subscribe(respose => {
      console.log(respose.data);
      return resolve(respose.data);
    }, (err: HttpErrorResponse) => {
      return reject(err);
    });
});
return promise;

}

}

My component TS:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { AuthService } from '../common-services/auth/auth.service';
import { UserService } from '../common-services/user.service';
import { Title } from '@angular/platform-browser';
import { SchoolsModel } from '../models/school-model';
import { SchoolsService } from '../business-services/schools.service';
import { GradesService } from '../business-services/grades.service';

declare const $;
@Component({
selector: 'app-divisions',
 templateUrl: './divisions.component.html',
styleUrls: ['./divisions.component.css'],
encapsulation: ViewEncapsulation.Emulated
})
export class DivisionsComponent implements OnInit {

  public divisionList: SchoolsModel;

constructor(
private schoolService: SchoolsService,
private gradesService: GradesService,
private titleService: Title,
private authService: AuthService,
private route: ActivatedRoute
) {}

ngOnInit(): void {

         this.getSchoolGrades();

}

private getSchoolGrades(schoolId: number) {
this.gradesService.getSchoolGrades(schoolId)
  .then((division: SchoolsModel) => {
   // debugger;
    this.divisionList = division;
  }).catch(err => {
    console.error("Error occured :", err)
  })
}


}

My component HTML

<div>
<button name="American Primary" 
class="choose-list arrow-onclick1" data-toggle="collapse" data-
target="#list1">
{{divisionList.name}}<i class="fa fa-arrow-right pull-
right arrow-down-onclick1" aria-hidden="true" style="margin-top: 
12px"></i>
</button>
<a routerLink="/editaisdivision" 
style="text-decoration: none;"><span class="fa fa-pencil pen-pen-pen" 
aria-hidden="true" style="margin-left: 10px; color: #171b5e;"></span>
</a>
</div>

Schools Model:

export class SchoolsModel{
id:number;
name:string;
logo:string;
vision:string;
mission:string;
address:string;
latitude:number;
longitude:number;
district_id:number;
created_at:Date;
updated_at:Date;
}

Environment:

export const environment = {
apiBaseUrl: 'https://crm.easyschools.org'
 }

I guess this is everything you might need to tell me why component is not catching the right data from the web service and displaying it on the screen.

I'm trying to be as specific as i can so if something is not clear just tell me.


Solution

  • Using promises is not really the optimal solution when you have such a powerful instrument as RxJs, especially since it's what Angular uses to handle http requests. Try to rewrite your service as follows:

    public getSchoolGrades(schoolId: number) {
        const apiUrl: string = environment.apiBaseUrl + 
    '/api/en/admin/grades/division';
        return this.http.get(apiUrl, { params: new HttpParams().set("school_id", schoolId.toString()) });
    }
    

    Then in your component:

    ngOnInit(): void { 
        this.getSchoolGrades(123);
    }
    
    private getSchoolGrades(schoolId: number) {
        this.gradesService.getSchoolGrades(schoolId)
            .catch(err => {
                console.error("Error occured :", err)
            })
            .subscribe((division: SchoolsModel) => {
                this.divisionList = division;
            });
    }