需要使用Angular 4服务从Web服务获取数据

时间:2018-02-12 16:38:24

标签: angular web-services typescript data-binding angular-services

我创建了一项服务,通过向后端发送特定ID然后获取有关所选ID的数据来帮助我从Web服务中提取详细信息, 我创建了一个函数来调用服务,现在我想知道我的代码中缺少什么。

我的服务:

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;

}

}

我的组件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)
  })
}


}

我的组件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>

学校模特:

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

环境:

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

我想这就是你可能需要告诉我为什么组件没有从Web服务中捕获正确的数据并将其显示在屏幕上的所有内容。

我正努力尽可能具体,如果有什么不明确的话,请告诉我。

3 个答案:

答案 0 :(得分:1)

当你拥有像RxJ这样强大的工具时,使用promises并不是最佳解决方案,特别是因为它是Angular用来处理http请求的。尝试按如下方式重写您的服务:

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

然后在你的组件中:

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

答案 1 :(得分:0)

您的方法签名就是这个

getSchoolGrades(schoolId: number)

但是在ngOnInit中你调用的方法没有通过schoolId

this.getSchoolGrades();

答案 2 :(得分:0)

这是调用网络服务并获得结果的简单方法

let token="Bearer"+" "+tokenUser;
    var headers = new Headers();
    headers.append('Authorization',token);
    headers.append('Content-Type','application/json');
    let options = new RequestOptions({ headers: headers });
    this.spinnerService.show();
    this.http.get('https://www.000webhost.com/sample/rest_api/api/all-user-details',options)
    .subscribe((res)=> {
         this.spinnerService.hide();            
         this.userdetails=res.json();

         console.log(this.userdetails);  

      }
        ,(err) => {
        this.spinnerService.hide();
        console.log("Error occured");
      });         
  }



  <tbody>
       <tr *ngFor = "let user of userdetails; let i=index">                   
       <td align="left" valign="middle">{{i+1}}</td>

       <td align="left" valign="middle">{{user.IPADDRESS}}</td> 
       <td align="left" valign="middle">{{user.INSERT}}</td>     
       <td align="left" valign="middle">{{user.UPDATE}}</td>     
      </tr> 
</tbody>