【问题标题】:Angular 5 Http Post Not workingAngular 5 Http Post 不工作
【发布时间】:2018-09-27 03:43:13
【问题描述】:

我正在使用 Angular 5 服务调用 POST API

服务文件

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse, HttpClientModule } from '@angular/common/http';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { HttpResponse } from 'selenium-webdriver/http';
import { IScheduleAPI } from '../interfaces/ischeduleAPI';
// import { Ischedule } from '../interfaces/ischedule';

@Injectable()
export class SchedulesService {
  apiURL = 'http://localhost:57863/api/Audit/';
  ScheduleDetail: IScheduleAPI[] = [];

  constructor(private http: Http) { }

  GetScheduleAPI(params, httpOptions) {
   return this.http.post<IScheduleAPI[]>(this.apiURL, params, httpOptions)
    .catch(this.errorHandler);
  }

  errorHandler(error: HttpErrorResponse) {
    return Observable.throw(error.message || 'Server Error');
  }
}

我在我的组件中调用此服务

import { Component, OnInit } from '@angular/core';
import { HttpClientModule, HttpHeaders } from '@angular/common/http';
import { IScheduleAPI } from '../interfaces/ischeduleAPI';
import { SchedulesService } from '../services/schedules.service';
import { Http, Response } from '@angular/http';

@Component({
  selector: 'app-schedules',
  templateUrl: './schedules.component.html',
  styleUrls: ['./schedules.component.css']
})
export class SchedulesComponent implements OnInit {
  Schedule: IScheduleAPI[];
  message: string;

  constructor(private sch: SchedulesService, private http: Http) { }

  ngOnInit() {
    const params = [{
      'ActionMethod': 'GetSchedule',
      'StaffCode': 'NA',
      'Password': 'NA'
    }];
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
    this.sch.GetScheduleAPI(params, httpOptions).subscribe(data => this.Schedule = data,
      error => this.message = error);
  }
}

现在的问题

1.] 显示错误,Expected 0 type arguments but got 1 in line

return this.http.post<IScheduleAPI[]>(this.apiURL, params, httpOptions)

它的内部服务文件,这是我从其他工作正常的服务文件中使用的标记。

删除 IScheduleAPI[] 后,它停止显示错误,但没有命中 API,而是显示错误

我正在使用 Angular 5

【问题讨论】:

  • 您正在混合旧的 Http 和新的 HttpClient 模块
  • Http 已弃用,请改用HttpClient
  • 只需将constructor(private http: Http) { } 替换为constructor(private http: HttpClient) { }。看起来您已经正确导入了
  • @David ,它使用 HttpClient 编译并点击 api 但它不等待 api 返回结果,在结果返回之前执行其他语句
  • @Jack : 返回前执行了哪些代码?你知道http请求是异步的吧?

标签: angular angular5


【解决方案1】:

您看起来好像在到处使用新的HttpClient,但在构造函数中。

你需要做的就是替换

constructor(private http: Http) { }

constructor(private http: HttpClient) { }

SchedulesServiceSchedulesComponent

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2018-08-18
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多