Javascript 如何在angular 6中发送ajax请求?

Javascript 如何在angular 6中发送ajax请求?,javascript,ajax,angular,request,Javascript,Ajax,Angular,Request,我完全不熟悉angular,因为我是后端开发人员。为了测试我的api,我需要从angular发送一个ajax请求。 告诉我怎么做? 有一个密码。必须在清除localeStorage之前执行请求 <button (click)="logoutAndClose()" class="btn_green btn_ml" mat-raised-button> Log out </button> 注销 @组件({ 选择器:“应用程序注销模式”, templateUrl:'.

我完全不熟悉
angular
,因为我是
后端开发人员。为了测试我的
api
,我需要从
angular
发送一个ajax请求。 告诉我怎么做? 有一个密码。必须在清除
localeStorage
之前执行请求

<button (click)="logoutAndClose()" class="btn_green btn_ml" mat-raised-button>
  Log out
</button>

注销
@组件({
选择器:“应用程序注销模式”,
templateUrl:'./logout modal.component.html',
样式URL:['./注销模式.component.scss']
})
导出类LogoutModalComponent实现OnInit{
构造函数(公共thisDialogRef:MatDialogRef,
专用路由器:路由器,
私有http:HttpClient,
@注入(MAT_对话框_数据)公共数据:任意){
}
恩戈尼尼特(){
}
logoutAndClose():void{
这是http.post(“http://127.0.0.1:8001/api/v1/users/settings/logout/")
localStorage.clear();
this.thisDialogRef.close();
this.router.navigateByUrl(RouteUrls.Login);
}
}

作为最佳实践,您应该创建一个服务来发送HTTP请求:

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));
  }
}
更新:

为了执行http查询,您需要运行它。所以您需要调用
subscribe
方法:

this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")
         .subscribe(s => console.log(s));
此外,作为最佳实践,不应包含http请求的实现细节,因为它不是视图处理。视图应该只显示数据

  • 您需要导入HTTPModule

    @NGD模块({ 进口:[ 浏览器模块, //在BrowserModule之后导入HttpClientModule。 HttpClientModule, ],

  • 在构造函数内注入:

    @可注射() 出口类服务{ 构造函数(私有http:HttpClient){} }

  • this.http.get(this.url).subscribe((数据:canbedirectlymatojsonobject)=>{ }))


  • 有关更多详细信息,请参考angular的http客户端。http客户端与可观察的http客户端配合使用,如果您不知道这些是什么,我建议您参加angular教程。您只需订阅post请求,直到没有请求到达端点为止
    export class YourCarComponent {
        constructor(private yourService: YourService) {
        }
    
        getCars(id: number) {
           this.yourService.get(id)
               .subscribe(s=> console.log(s));
    }
    
    this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")
             .subscribe(s => console.log(s));