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

我完全不熟悉,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);

  }

}


ITMISS
浏览 194回答 2
2回答

慕斯王

作为最佳实践,您应该创建一个服务来发送 HTTP 请求:import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';@Injectable()export class YourService {&nbsp; private url: string = "http://api";&nbsp; private endpoint:string = "car";&nbsp; constructor(private http: HttpClient,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;) { }&nbsp; get(id: number): Observable<Car> {&nbsp; &nbsp; &nbsp; return this.httpClient&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .get<Car>(`${this.url}/${this.endpoint}/${id}`)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .pipe(map(data => data));&nbsp; }}然后你就可以在你的组件中使用内置的依赖注入:export class YourCarComponent {&nbsp; &nbsp; constructor(private yourService: YourService) {&nbsp; &nbsp; }&nbsp; &nbsp; getCars(id: number) {&nbsp; &nbsp; &nbsp; &nbsp;this.yourService.get(id)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.subscribe(s=> console.log(s));}更新:为了执行您的 http 查询,您需要运行它。所以你需要调用subscribe方法:this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.subscribe(s => console.log(s));此外,作为最佳实践,不应包含 http 请求的实现细节,因为它不是处理视图。视图应该只显示数据。

慕码人2483693

您需要导入 HTTPModule@NgModule({ 导入: [ BrowserModule, // 在 BrowserModule 之后导入 HttpClientModule.HttpClientModule, ],在构造函数中注入:@Injectable() 导出类 YourService { 构造函数(私有 http: HttpClient) { } }this.http.get(this.url).subscribe((data: CanBeDirectlyMapToJsonObject) => { });有关更多详细信息,请参阅https://angular.io/guide/http
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript