首页 > 解决方案 > Angular 6:将 POST 请求从 Http 更新到 HttpClient

问题描述

我正在将我的 Angular 应用程序从 Angular 4 升级到 6,这意味着我将替换HttpHttpClient. 使用 Angular 4 的 POST 请求工作得非常好,但我在使用 Angular 6 时遇到了一些麻烦。

api.service.ts

import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { map, catchError } from 'rxjs/operators';
import { throwError, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(
    private http: HttpClient
  ) { }

    post(path: string, body: any): Observable<any> {
    const url = environment.api_url + '/' + path;
    return this.http.post(url,
      body
    )
    .pipe(map((res: Response) => res.json()), catchError((error: Response) => throwError(error.json())));
    }
}

app.component.ts

public sendEnquiry() {
    this.sendingEnquiry = true;
    if (
        this.enquiry.college.length > 0 &&
        this.enquiry.university.length > 0 &&
        this.enquiry.official_email.length > 0 &&
        this.enquiry.official_person.length > 0 &&
        this.enquiry.user_name.length > 0 &&
        this.enquiry.user_email.length > 0 &&
        this.enquiry.user_type.length > 0
      ) {
      this.apiService.post('univinks/college_enquiry', this.enquiry)
      .subscribe( (res) => {
        console.log(res.message);
        this.showSuccessToast(res.message);
        this.sendingEnquiry = false;
        this.router.navigate(['']);
      }, (err) => {
        console.log(err);
        this.showErrorToast('Some error occurred. Enquiry not sent');
        this.sendingEnquiry = false;
      });
    } else {
      this.showErrorToast('Incomplete Enquiry Form');
      this.sendingEnquiry = false;
    }
  }

这工作正常,并按预期向用户发送包含查询详细信息的电子邮件。问题是它显示错误 toast “发生了一些错误。查询未发送”,而不是显示成功 toast 并导航到主路由''。我在这里想念什么?

标签: angular-httpclient

解决方案


推荐阅读