Angular 6:将POST请求从Http更新到HttpClient

时间:2019-01-10 10:27:27

标签: angular-httpclient

我将Angular Application从Angular 4升级到6,这意味着我将Http替换为HttpClient。 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并导航到本地路线“”。我在这里想念什么?

0 个答案:

没有答案