Search code examples
javascriptajaxangularrequest

How to send an ajax request in the angular 6?


I am completely unfamiliar with the angular since I am a back-end developer. To test my api, I need to send an ajax request from angular. Tell me how to do this? There is a code. The request must be executed before clearing the localeStorage.

<button (click)="logoutAndClose()" class="btn_green btn_ml" mat-raised-button>
  Log out
</button>
@Component({
  selector: 'app-logout-modal',
  templateUrl: './logout-modal.component.html',
  styleUrls: ['./logout-modal.component.scss']
})
export class LogoutModalComponent implements OnInit {

  constructor(public thisDialogRef: MatDialogRef<LogoutModalComponent>,
              private router: Router,
              private http: HttpClient,
              @Inject(MAT_DIALOG_DATA) public data: any) {
  }

  ngOnInit() {
  }
  logoutAndClose(): void {
    this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")
    localStorage.clear();
    this.thisDialogRef.close();
    this.router.navigateByUrl(RouteUrls.Login);
  }
}

Solution

  • As a best practice you should create a service to send HTTP requests:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class YourService {
      private url: string = "http://api";
      private endpoint:string = "car";
    
      constructor(private http: HttpClient,
                 ) { }
    
    
      get(id: number): Observable<Car> {
          return this.httpClient
              .get<Car>(`${this.url}/${this.endpoint}/${id}`)
              .pipe(map(data => data));
      }
    }
    

    and then you will be available to use built in dependency injection in your component:

    export class YourCarComponent {
        constructor(private yourService: YourService) {
        }
    
        getCars(id: number) {
           this.yourService.get(id)
               .subscribe(s=> console.log(s));
    }
    

    UPDATE:

    In order to execute your http query, you need to run it. So you need to call subscribe method:

    this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")
             .subscribe(s => console.log(s));
    

    In addition, as a best practice should not contain an implementation details of http requests because it is not deal of view. View should just show data.