2 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
作為最佳實(shí)踐,您應(yīng)該創(chuàng)建一個(gè)服務(wù)來(lái)發(fā)送 HTTP 請(qǐng)求:
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));
}
}
然后你就可以在你的組件中使用內(nèi)置的依賴注入:
export class YourCarComponent {
constructor(private yourService: YourService) {
}
getCars(id: number) {
this.yourService.get(id)
.subscribe(s=> console.log(s));
}
更新:
為了執(zhí)行您的 http 查詢,您需要運(yùn)行它。所以你需要調(diào)用subscribe方法:
this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")
.subscribe(s => console.log(s));
此外,作為最佳實(shí)踐,不應(yīng)包含 http 請(qǐng)求的實(shí)現(xiàn)細(xì)節(jié),因?yàn)樗皇翘幚硪晥D。視圖應(yīng)該只顯示數(shù)據(jù)。

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
您需要導(dǎo)入 HTTPModule
@NgModule({ 導(dǎo)入: [ BrowserModule, // 在 BrowserModule 之后導(dǎo)入 HttpClientModule.HttpClientModule, ],
在構(gòu)造函數(shù)中注入:
@Injectable() 導(dǎo)出類 YourService { 構(gòu)造函數(shù)(私有 http: HttpClient) { } }
this.http.get(this.url).subscribe((data: CanBeDirectlyMapToJsonObject) => { });
有關(guān)更多詳細(xì)信息,請(qǐng)參閱https://angular.io/guide/http
添加回答
舉報(bào)