Angular4 - post form data to rest api

后端 未结 4 1193
星月不相逢
星月不相逢 2020-12-23 23:50

How is it possible to post form data to an external rest api?

At the moment i have an html form:

4条回答
  •  误落风尘
    2020-12-24 00:30

    How about using Typescript to make your life easier?

    The html has ngModel two way binding.I've changed to rename the form personForm. You can add validation, but I have skipped it here.

          
      
      
      
     
    

    On the component, you can use an interface Person which you can define in a models folder. The contents looks like this.

    export interface Person {
      id:number;
      firstName: string;
      lastName: string;
    }
    

    And then in the submit method you can map it automatically like below.

    onSubmit(person: Person){
      http.post('your_url', person).subscribe(status=> console.log(JSON.stringify(status)));
    }
    

    See how easy it is type safety? Also you can check if id is populated and either make a 'PUT' or 'DELETE' request depending on whether you want to update the person or delete.

提交回复
热议问题