Monday 9 November 2020

how to convert ajax post call api in angular8

Client given below Ajax call to post the data to there server, but I am not able to understand how to convert this call into component.ts and servervice

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script type="text/javascript">
 $.ajax
 ({
  type: "POST",
  url: 'https://xyz/client/schedule',
  contentType: 'application/json',
  data: JSON.stringify({
    "apiKey": "myapikey"
  }),
  dataType : 'json',
  headers: {
  'authorization': '<?php echo $authorization; ?>'
  },
  success: function(retval)
  {
  // alert(retval);
  console.log(retval);
  // var success = retval.success;
  }
  });
  </script>

I have updated Question and added after two replied answer

Below is my model class

export class Schedule1 {

classTitle: string;
classInfo: string;
classDateTime: string;
timezone: string;
classDuration: number;
classRecording:string;
classAutoStart: boolean;
recordingAutoStart: boolean;
classVideoRes: number;
    
   constructor() {
    
      
   }

  }

Below is component.ts on button click passing static values

import { Schedule1 } from '../Models/Schedule1.model'


   Schedule1: Schedule1 = new Schedule1();

    addSchedule(scheduleForm: NgForm): void {

    //static data parameter passing
    this.Schedule1.classTitle='hi Class on 3rd April, 2020';
    this.Schedule1.classInfo= 'This is a demo class scheduled to understand API';
    this.Schedule1.classDateTime= '2020-11-12 11:30 AM';
    this.Schedule1.timezone= 'Asia/Kolkata';
    this.Schedule1.classDuration= 15;
    this.Schedule1.classRecording= 'yes';
    this.Schedule1.classAutoStart= false;
    this.Schedule1.recordingAutoStart= false;
    this.Schedule1.classVideoRes= 720;


    //const data = JSON.stringify(this.Schedule1);
    const data = { 
    apiKey: "dcbf187d-bdfe-431b-8f60-fa19bf51cd85", 
    data:  JSON.stringify(this.Schedule1)
    } 

    this.subscription = this.userSvc
    .fetchData("https: //xyz.com/client/schedule", data)
    .subscribe(
    data => {
    // Data on Success
    console.log("data", data);
    },
    error => {
    console.log("error", error);
    }
    );

    }

Below is service.ts

  fetchData(url: string, data: any): Observable<any> {
    const headers = {
    
    Authorization: "Bearer "+"1234",
     "My-Custom-Header": "foobar",
    contentType: "application/json"
    };

   return this.http.post(url, data, {
    headers
    });
   }

in console getting this error.

enter image description here



from how to convert ajax post call api in angular8

No comments:

Post a Comment