目前,Angular已经将旧的http模块替换为common/http模块,建议使用HttpClient和HttpRequest类来代替旧的RequestOptions和RequestMethod。以下是一些示例代码:
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable() export class MyService { constructor(private http: HttpClient) {}
getData() { const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.get('my-url', { headers }); }
postData(data) { const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post('my-url', data, { headers }); } }
在示例代码中,我们使用HttpClient和HttpHeaders类来设置请求头信息,并利用这些类向服务器发送get和post请求。这些类可以很好地管理请求和响应,并提供易于使用的API来处理http请求。