typescript - 为什么 Angular 教程不需要导入 Observable
如果你看看这里的 Angular 教程,它们不像其他人那样导入 observable,而且它们也没有导入它们的 authService。
这是我做的最低限度操作,让 TypeScript 不再抱怨:
import { AuthService } from './auth.service';
import { Observable } from 'rxjs/Observable';
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);
}
}
他们是在做我没有做的事情,还是他们只是为了让教程少两行而跳过了导入步骤。
答案#1
它只是没有在那里显示,为了代码可读性,但如果你浏览他们的教程:
https://angular.io/tutorial/toh-pt6#rxjs-imports
有一个指向实时演示的链接:Plnkr
在这里你可以清楚地看到所有的导入
文件:app/hero-search.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
答案#2
这是我为了让 TypeScript 不抱怨而做的最基本操作
这是正确的版本。Angular 文档简直不准确/过时了。给他们发一个 PR 🌹
