Angular10--服务

498 阅读1分钟

HttpClinet使用

  • 1、在跟模块导入HttpClient,这个应用值需导入一次,不要在其它模块导入
  • 2、在构造函数中注入HttpClient。http具有get/post/put/detelet等方法,不规范的请求使用request方法
  • 3、返回的值是Obserable。必须订阅,才会发送请求,否则不会发送

services/home.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class HomeService {
  constructor(private http: HttpClient) { }
  getTabs(){
    return this.http.get(`${environment.baseUrl}/tabs`, {
      params: {icode: `${environment.icode}`}
    });
  }
}

在模块中声明

@NgModule({
  declarations: [	
  	...
    HomeService
  ]
})
export class AppModule {}

在组件中使用

export class AppComponent implements OnInit{
  constructor(private service: HomeService){}
  ngOnInit(){
    this.service.getTabs().subscribe(ret=> {
      console.log(ret)
    })
  }
}