我正在开发一个项目,该项目需要迁移旧 Http 的所有实例以利用 Angular 提供的新 HttpClient。异步方法在 DataService 类中声明如下:
@Injectable()
export class DataService {
constructor(private http: Http) { }
async getAsync<T>(resource: string, options?: RequestOptions): Promise<T> {
return this.http
.get(resource, options)
.map((response: Response) => response.json())
.catch(this.handleError).toPromise();
}
Run Code Online (Sandbox Code Playgroud)
并在另一个服务类中使用,如下所示:
async getUser() {
try {
this.logger.debug('Getting User State...');
const userInfo = await this.dataService.getAsync<[Type Parameter]>(
this.constantService.urls.authenticatedUserUri, <RequestOptions>{ withCredentials: true }
);
this.logger.debug(JSON.stringify(userInfo));
this.authorizeUser(userInfo);
} catch (error) {
this.logger.debug(error);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道为了使用 HttpClient,我需要在提供 DataService 类的模块中导入 HttpClientModule,然后在服务本身中导入 HttpClient 并通过类的构造函数注入它。我也知道该行.map((response: Response) => response.json() )是不必要的,因为 JSON …