为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2021-11-12 17:23:07
我完全不熟悉,angular因为我是back-end开发人员。为了测试我的api,我需要从angular. 告诉我怎么做?有一个代码。请求必须在清除之前执行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);  }}
查看完整描述

2 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

作为最佳实践,您应该创建一个服务来发送 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));

  }

}

然后你就可以在你的组件中使用内置的依赖注入:


export class YourCarComponent {

    constructor(private yourService: YourService) {

    }


    getCars(id: number) {

       this.yourService.get(id)

           .subscribe(s=> console.log(s));

}

更新:


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


this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")

         .subscribe(s => console.log(s));

此外,作为最佳实践,不应包含 http 请求的实现细节,因为它不是处理视图。视图应该只显示数据。


查看完整回答
反对 回复 2021-11-12
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

  1. 您需要导入 HTTPModule

    @NgModule({ 导入: [ BrowserModule, // 在 BrowserModule 之后导入 HttpClientModule.HttpClientModule, ],

  2. 在构造函数中注入:

    @Injectable() 导出类 YourService { 构造函数(私有 http: HttpClient) { } }

  3. this.http.get(this.url).subscribe((data: CanBeDirectlyMapToJsonObject) => { });

有关更多详细信息,请参阅https://angular.io/guide/http


查看完整回答
反对 回复 2021-11-12
  • 2 回答
  • 0 关注
  • 193 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信