Angular 4.3.0-rc.0 版本已经发布🐦。在这个版本中,我们等到了一个令人兴奋的新功能 - HTTPClient API 的改进版本,以后妈妈再也不用担心我处理 HTTP 请求了😆。
HttpClient 是已有 Angular HTTP API 的演进,它在一个单独的 @angular/common/http
包中。这是为了确保现有的代码库可以缓慢迁移到新的 API。
接下来让我们开启 Angular 新版Http Client 之旅。
安装
首先,我们需要更新所有的包到 4.3.0-rc.0
版本。然后,我们需要在 AppModule
中导入 HttpClientModule
模块。具体如下:
import { HttpClientModule } from '@angular/common/http';@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], bootstrap: [AppComponent]})export class AppModule { }
现在一切准备就绪。让我们来体验一下我们一直期待的三个新特性。
特性一 默认 JSON 解析
现在 JSON 是默认的数据格式,我们不需要再进行显式的解析。即我们不需要再使用以下代码:
http.get(url).map(res => res.json()).subscribe(...)
现在我们可以这样写:
http.get(url).subscribe(...)
特性二 支持拦截器 (Interceptors)
拦截器允许我们将中间件逻辑插入管线中。
请求拦截器 (Request Interceptor)
import { HttpRequest, HttpHandler, HttpEvent} from '@angular/common/http';@Injectable()class JWTInterceptor implements HttpInterceptor { constructor(private userService: UserService) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const JWT = `Bearer ${this.userService.getToken()}`; req = req.clone({ setHeaders: { Authorization: JWT } }); return next.handle(req); }}
如果我们想要注册新的拦截器 (interceptor),我们需要实现 HttpInterceptor
接口,然后实现该接口中的 intercept
方法。
export interface HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;}
需要注意的是,请求对象和响应对象必须是不可修改的 (immutable)。因此,我们在返回请求对象前,我们需要克隆原始的请求对象。
next.handle(req)
方法使用新的请求对象,调用底层的 XHR 对象,并返回响应事件流。
响应拦截器 (Response Interceptor)
@Injectable()class JWTInterceptor implements HttpInterceptor { constructor(private router: Router) {} intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> { return next.handle(req).map(event => { if (event instanceof HttpResponse) { if (event.status === 401) { // JWT expired, go to login } } return event; } }}
新闻热点
疑难解答
图片精选