由于我们使用JSON格式作为数据,因此我遵循了tutorial。为了通过URL调用我们的API,需要设置API密钥以获取/读取数据。是否可以通过任何方法设置API密钥或将Headers设置为Angular Ionic APP,以便可以像使用邮递员进行测试一样从API URL获取和读取数据?
这是我的data.service代码
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
url = '';
apiKey = ''; // <-- Enter your own key here!
constructor(private http: HttpClient){}
getLocalData(){
return this.http.get("assets/data/data.json");
}
getRemoteData(){
return this.http.get('{this.url}&apiKey=${this.apiKey}');
}
}
这是我的page.ts代码
import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
@Component({
selector: 'app-status',
templateUrl: './status.page.html',
styleUrls: ['./status.page.scss'],
})
export class StatusPage implements OnInit {
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getLocalData().subscribe(data => {
console.log("Local Data:");
console.log(data);
});
this.dataService.getRemoteData().subscribe(data => {
console.log("Remote Data:");
console.log(data);
});
}
}
您可以将其设置为HttpHeaders,因此您需要使用
let headers = new HttpHeaders().set('apiKey', this.apiKey);
或
let headers = new HttpHeaders({'apiKey': this.apiKey});
您可以将其设置为,
this.http.get(this.apiUrl, {headers: headers})