Home > Enterprise >  How to insert a current date in a url using Angular
How to insert a current date in a url using Angular

Time:12-22

I'm a little lost here , I want to insert a current date into an api url using angular . This is what i have done so far.

Here's my Ts

import { HttpClient} from '@angular/common/http';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-matches',
  templateUrl: './matches.component.html',
  styleUrls: ['./matches.component.css']
})
export class MatchesComponent implements OnInit {
public myMatches: any = []
myDate = new Date();
  constructor( private http: HttpClient , public datePipe: DatePipe) { 
    let myDates = this.datePipe.transform(this.myDate, 'yyyy-MM-dd');
  }
getMyMatches(){
  const url = "https://app.sportdataapi.com/api/v1/soccer/matches?apikey=myKey&season_id=1980&date_from= myDates"
  return this.http.get(url).subscribe((res)=>{
    this.myMatches =res
    console.log(res);
    
  })
}
  ngOnInit(): void {
    this.getMyMatches()
  }
}```

In my browser console i get 500 response status. DatePipe has been added in app module's  providers .

CodePudding user response:

The error is not in DatePipe.

@Component({
  selector: 'app-matches',
  templateUrl: './matches.component.html',
  styleUrls: ['./matches.component.css']
})
export class MatchesComponent implements OnInit {
public myMatches: any = []
myDates: any;

  constructor( private http: HttpClient , public datePipe: DatePipe) { 
    this.myDates = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
  }
getMyMatches(){
  const url = "https://app.sportdataapi.com/api/v1/soccer/matches?apikey=myKey&season_id=1980&date_from="   this.myDates;
  return this.http.get(url).subscribe((res)=>{
    this.myMatches =res
    console.log(res);
    
  })
}
  ngOnInit(): void {
    this.getMyMatches()
  }
}

CodePudding user response:

You have to use string interpolation. Try this

 const url = `https://app.sportdataapi.com/api/v1/soccer/matches?apikey=myKey&season_id=1980&date_from=${ myDates}`
  • Related