Angular Ionic中的API键

问题描述 投票:0回答:1

由于我们使用JSON格式作为数据,因此我遵循了tutorial。为了通过URL调用我们的API,需要设置API密钥以获取/读取数据。是否可以通过任何方法设置API密钥或将Headers设置为Angular Ionic APP,以便可以像使用邮递员进行测试一样从API URL获取和读取数据?

enter image description here

这是我的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);
    });
  }


}
angular api ionic-framework api-key
1个回答
0
投票

您可以将其设置为HttpHeaders,因此您需要使用

let headers = new HttpHeaders().set('apiKey', this.apiKey);

let headers = new HttpHeaders({'apiKey': this.apiKey});

您可以将其设置为,

this.http.get(this.apiUrl, {headers: headers})
© www.soinside.com 2019 - 2024. All rights reserved.