当前位置: 首页 > 工具软件 > angular-token > 使用案例 >

angular-http发送请求

李兴为
2023-12-01



//module.ts 文件
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, HttpClientJsonpModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

//component.ts 文件
import {HttpClient,HttpClientJsonpModule } from "@angular/common/http"; //导入http模块,HttpClientJsonpModule  为JSONP请求导入的模块

constructor(public http:Httpclient) {}  //构造函数中声明


const  url= "http://XXXX";

//get请求
this.http.get(url).subscribe (response =>{
    console.log(response);
})

//get 获取完整请求体 { observe: 'response' }
this.http.get(url,{ observe: 'response' }).subscribe (response =>{
    console.log(response);
})

//post请求
const httpOptions = {  //请求头
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    Authorization: 'my-auth-token'
  })
};
let params = {"age":22,"username":"zl"}  //携带的参数
this.http.post(url, params,httpOPtions)
  .subscribe((response)=>{
    console.log(response)
  })


//处理错误
getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      catchError(error => this.handleError(error))  //把error传入进行处理
    );
}

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an observable with a user-facing error message
  return throwError(
    'Something bad happened; please try again later.');
};


// JSONP跨域请求 需要后端支持

this.http.jsonp.(url,'callback').subscribr((response)=>{  //callback为后端定义字段,一般是callback,cb
console.log(response)
})

参考文档:https://www.w3cschool.cn/angulerten/angulerten-iue237zd.html

                  https://angular.cn/guide/http#making-a-post-request

 类似资料: