如何从angular的有效Web API获取数据?

时间:2019-05-20 17:10:31

标签: c# angular typescript api web

好的,所以我试图从Web API中获取以角度生成的数据。 Web API工作正常,我使用Postman进行了测试,Postman从Web API获取数据就很好了,这是Postman从Web API“ http://prntscr.com/nr18ct获取数据的屏幕截图。这使我确定这是角度问题。而且,如果我没有任何道理,或者如果第一次在这里提出问题时还没有解决其余的问题,我将感到抱歉。

我确实遵循了Angular.io上的角度教程,我真的不知道它会导致什么,只是说在我完成教程的最后一部分(试图从Web API获取数据)之前,它工作得非常好。我的第一个想法可能是我在Angled(打字稿类)的PagedVehicleMake类或在Angle也是打字稿类的VehicleMake类中找到了一些东西

Web API部分: 如您在屏幕快照中所见,我是在Web API发送此类数据之前发送的。

    public class PagedResult<T> : IPagedResult<T> where T : class
{
        public int PageNumber { get; set; }
        public int PageSize { get; set; }
        public int TotalNumberOfPages { get; set; }
        public IEnumerable<T> Results { get; set; }
}

和IEnumrable结果在这种情况下是IEnumrable结果 VehicleMakeVM是:

    public class VehicleMakeVM
{
        public int Id { get; set; }
        public string Name { get; set; }
        public string Abrv { get; set; }
}

现在为角部分:

export class PagedVehicleMake{
    Results : VehicleMake[];
    TotalNumberOfPages : number;
    PageSize : number;
    PageNumber : number;
}

我试图以与发送数据到邮递员相同的方式安排PagedVehicleMake类,该过程在我发送的屏幕快照中显示。我以为可能与此有关。

export class VehicleMake {
    Id : number;
    Name : string;
    Abrv : string;
}

这是Angle中的VehicleMakeService类:

export class VehicleMakeService {

  constructor(private http: HttpClient, private messageService : MessageService) { }
  private vehiclemakesUrl = "http://localhost:53282/api/VehicleMake"
  /**GET vehiclemakes from the server */
  getVehicleMakes() : Observable<PagedVehicleMake>{
    this.messageService.add("VehicleMakeService : fetched VehicleMakes")
    return this.http.get<PagedVehicleMake>(this.vehiclemakesUrl).pipe(
      catchError(this.handleError<PagedVehicleMake>("getVehicleMakes", []))
      );
  }
    /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
    /** Log a VehicleMakeService message with the MessageService */
    private log(message: string) {
      this.messageService.add(`VehicleMakeService: ${message}`);
    }

我希望它只能从WebAPI中获取数据,但是某种程度上它无法获取数据。

1 个答案:

答案 0 :(得分:0)

我发现了问题所在。实际上就是WebAPI,我忘了启用CORS,仅此而已。