1. 依赖注入:是一种编程模式,可以让类从外部源中获得它的依赖,而不必亲自创建它们
父子间同一个服务只需注入一次依赖注入的实例
自动依赖注入: 无论通过像<hero-list></hero-list>
这样的 HTML 标签还是通过路由导航到组件 —— 它都会自己管理好注入器的创建和调用
2, httpClient拦截可为所有的请求统一设置表头
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
简捷写法:const authReq = req.clone({setHeaders: {Authorization: authHeader}});