service.ts文件:
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { throwError } from 'rxjs'; import { catchError } from 'rxjs/operators';
@Injectable({ providedIn: 'root' }) export class ApiService {
private apiURL = 'http://localhost:3000';
constructor(private http: HttpClient) { }
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
Backend returned code ${error.status},
+
body was: ${error.error}
);
}
return throwError(
'Something bad happened; please try again later.');
};
//以下是一个发出POST请求的方法
postData(data) {
return this.http.post(${this.apiURL}/myData
, data)
.pipe(
catchError(this.handleError)
)
}
}
component.ts文件:
import { Component } from '@angular/core'; import { ApiService } from './api.service';
@Component({
selector: 'app-root',
template:
,
})
export class AppComponent {Post Data to API
title = 'app'; myData = {name: 'John', age: 30};