下面是一个使用Angular 7从API调用中获取响应的示例代码:
npm install -g @angular/cli
ng new my-app
cd my-app
ng generate service api
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
apiUrl = 'https://api.example.com';
constructor(private http: HttpClient) { }
getData() {
return this.http.get(this.apiUrl);
}
}
import { Component } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
template: `
- {{ item }}
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
data: any[];
constructor(private apiService: ApiService) { }
getData() {
this.apiService.getData().subscribe((response: any) => {
this.data = response;
});
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
ng serve
现在,当你点击"Get Data"按钮时,应用程序将从API调用中获取响应,并将数据显示在页面上。请记得将apiUrl
替换为你自己的API地址。