2 回答
![?](http://img1.sycdn.imooc.com/533e4c640001354402000200-100-100.jpg)
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 请求的实现细节,因为它不是处理视图。视图应该只显示数据。
![?](http://img1.sycdn.imooc.com/545861b80001d27c02200220-100-100.jpg)
TA贡献1860条经验 获得超9个赞
您需要导入 HTTPModule
@NgModule({ 导入: [ BrowserModule, // 在 BrowserModule 之后导入 HttpClientModule.HttpClientModule, ],
在构造函数中注入:
@Injectable() 导出类 YourService { 构造函数(私有 http: HttpClient) { } }
this.http.get(this.url).subscribe((data: CanBeDirectlyMapToJsonObject) => { });
有关更多详细信息,请参阅https://angular.io/guide/http
添加回答
举报