【问题标题】:How to retrieve a form POST response on angular 8 [closed]如何在角度 8 上检索表单 POST 响应 [关闭]
【发布时间】:2019-12-30 13:22:14
【问题描述】:

在 html 表单上进行 POST 调用后如何检索服务器的服务器响应?

<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>

【问题讨论】:

标签: json angular forms post server


【解决方案1】:

作为一种好的做法,考虑使用向服务器发送数据并从服务器获取响应的服务。

来自the Angular docs的示例:

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'))
        );
    }
}

你的组件.ts:

constructor(private heroService:  HeroService ) {  }

create(){
    this.heroService.addHero( yourObject ).subscribe(resp => {
        console.log(resp)
    }) 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多