HttpClient Service 服务对象
HttpClient 服务对象用于向指定的URL发起异步请求,使用步骤
- 在主模块中导入HttpClient服务所在的模块
// app.module.ts
imports:[BrowserModule,FormsModule,HttpClientModule]
- 在需要使用异步请求的组件中声明依赖HttpClient服务对象,就可以使用该对象发起异步请求了
http:HttpClient
constructor(http:HttpClient){
this.http = http
}
// 使用
this.http.get(url).subscribe((res)=>{
console.log('得到了订阅的异步的响应数据',res);
})
服务简化工具
ng g service 服务名
服务对象的作用范围
声明服务提供者的方式:
方式1: 在根模块中提供的服务对象 --- 在整个应用中服务是单例的
@Injectable({providedIn:'root'})
exports class TimerService{}
方式2: 在组件中提供服务对象 --- 在每个组件中服务都是有一个实例的
@Injectable()
export class TimerService{}
---------------------------
@Component({
selector: '',
templateUrl: '',
providers:[TimerService]
})
export class LoginComponent{ }
注意:项目中只要服务对象中有属性,只能用方式2:;否则推荐使用方式1