在Angular 5中,可以使用HttpClient
模块来发送HTTP请求并订阅响应。下面是一个示例,演示如何订阅读取HTTP状态码204:
import { HttpClient } from '@angular/common/http';
// 在组件的构造函数中注入HttpClient
constructor(private http: HttpClient) {}
// 发送HTTP请求并订阅响应
this.http.get('https://example.com/api/data', { observe: 'response' })
.subscribe(response => {
// 检查状态码
if (response.status === 204) {
console.log('HTTP Status Code 204');
// 处理响应
// ...
} else {
console.log('Other HTTP Status Code');
// 处理其他状态码
// ...
}
}, error => {
console.error('Error occurred:', error);
// 处理错误
// ...
});
在上述示例中,我们使用HttpClient
的get
方法发送一个GET请求,并在{ observe: 'response' }
选项中设置observe
参数为'response'
,以获取完整的响应对象。
在subscribe
中,我们订阅了响应,并在回调函数中检查了响应的状态码。如果状态码为204,则输出"HTTP Status Code 204",否则输出"Other HTTP Status Code"。
请确保已经在Angular模块中导入了HttpClientModule
,并将HttpClient
添加到提供商数组中:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
// ...
})
export class AppModule { }
这样就可以在Angular 5中订阅读取HTTP状态码204了。