在 Angular11 中进行 HTTPS API 调用需要使用 HttpClient 模块。以下是一个使用 HttpClient 模块进行 HTTPS API 调用的示例代码:
首先在 app.module.ts 中引入 HttpClientModule:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
// ...
HttpClientModule,
],
// ...
})
export class AppModule { }
接下来,我们可以在组件中使用 HttpClient:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface ApiResponse {
// 定义接口数据格式
}
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
apiResponse: ApiResponse;
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get('https://example.com/api/data').subscribe(data => {
this.apiResponse = data;
});
}
}
在上述示例中,我们在组件中注入了 HttpClient,并使用 get 方法发起了一个 HTTPS 请求,并在请求成功后讲返回的数据赋值给了组件的变量 apiResponse。
这是一个简单的使用 HttpClient 模块进行 HTTPS API 调用的示例,可以根据实际需求进行更改和扩展。