在html表单上进行POST调用后,如何检索服务器的服务器响应? 答案 0 :(得分:2) 作为一种好的做法,请考虑使用将数据发送到服务器并从服务器获得响应的服务。 来自the Angular docs的示例: yourcomponent.ts:<form action="http://localhost:8080/upload" method="POST">
<label for="file">Choose File</label>
<input type="file"
id="file"
enctype="multipart/form-data">
<div *ngIf=badName>
<small id="emailHelp" class="form-text text-muted">Wrong file format. Only accepted format: csv.</small>
</div>
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
</form>
1 个答案:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Hero } from './hero';
import { MessageService } from './message.service';
@Injectable({ providedIn: 'root' })
export class HeroService {
private heroesUrl = 'api/heroes'; // URL to web api
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private http: HttpClient) { }
/** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, this.httpOptions).pipe(
tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
}
constructor(private heroService: HeroService ) { }
create(){
this.heroService.addHero( yourObject ).subscribe(resp => {
console.log(resp)
})
}