Search code examples
angulartypescriptionic4

How to store a variable in angular which is being subscribed via post as json?


I have a json as like this.

[{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}]

How to store date in a variable using angular which is being subscribe d as http request.I am not able to store .This is what i tried.

 date:string=[];
 sendPostRequest()  {

  var options = { headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) };
   var count=0;
  this.http.post("http://localhost/android/Api.php?apicall=getattendance", this.postData,options).
  pipe(map(res =>  res.results || []))

  .subscribe(data => {
   this.date=data['date'];


  });

please help me.I am new to angular.


Solution

  • You are getting response as an array. Convert your response to date. Please refer below code where you will get the date from your response.

    date:string=[];
     sendPostRequest()  {
    
      var options = { headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) };
       var count=0;
      this.http.post("http://localhost/android/Api.php?apicall=getattendance", this.postData,options).
      pipe(map(res =>  res.results || []))
    
      .subscribe(data => {
       this.date=data.map(ele => ele.date);
    
    
      });
    

    Example,

    const data = [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}];
    
    const date = data.map(ele => ele.date);
    
    console.log(date);