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



我创建了一个服务,以帮助我从Web服务中获取特定ID,然后将特定ID发送到后端,然后获取有关所选ID的数据,我创建了一个函数来调用该服务,现在我想知道我的代码中缺少什么。

我的服务:

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服务中捕获正确的数据并在屏幕上显示。

我试图尽我所能,因此,如果不清楚的话,请告诉我。

使用承诺并不是当您具有像RXJ这样的功能强大的仪器时,并不是真正的解决方案,尤其是因为它是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;
        });
}

您的方法签名是此

getSchoolGrades(schoolId: number)

但是在ngoninit中,您正在呼叫该方法而不通过schoolid

this.getSchoolGrades();

这是调用Web服务并获取结果

的简单方法
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>

相关内容

  • 没有找到相关文章

最新更新