【问题标题】:How do I receive data form the API with key and header in angular 8如何使用 Angular 8 中的密钥和标头从 API 接收数据
【发布时间】:2020-11-10 10:15:36
【问题描述】:

我正在尝试使用密钥和标头格式从 API 获取数据,但不知道如何执行此操作。当没有 header 时,我们使用服务中的 get 方法接收数据。

这是 api.service.ts 文件:

export class ApiService {
  API_KEY = 'key......';

getData(){
    return this.httpClient.get(`https://data.org/v2/somethig=ng?sources=sdfgghhhh&apiKey=${this.API_KEY}`);
  }

【问题讨论】:

    标签: angular angular8


    【解决方案1】:

    在你的组件中注入 ApiService

    接下来,打开 src/app/news/news.component.ts,或者你想使用getNews()方法的组件,文件并开始在你的组件中导入ApiService:

    import { ApiService } from '../api.service';
    

    接下来,需要通过组件的构造函数注入ApiService:

    import { Component, OnInit } from '@angular/core';
    import { ApiService } from '../api.service';
    @Component({
      selector: 'app-news',
      templateUrl: './news.component.html',
      styleUrls: ['./news.component.css']
    })
    export class NewsComponent implements OnInit {
    
      constructor(private apiService: ApiService) { }
    }
    

    发送 GET 请求并订阅 Observable 接下来定义一个articles变量,在组件的ngOnInit()方法中调用API服务的getNews()方法:

    export class NewsComponent implements OnInit {
      articles;
    
      constructor(private apiService: ApiService) { }
      ngOnInit() {
        this.apiService.getNews().subscribe((data)=>{
          console.log(data);
          this.articles = data['articles'];
        });
      }
    }
    

    这将确保在加载组件后获取我们的数据。

    我们调用 getNews() 方法并订阅返回的 Observable,它将向新闻端点发送 GET 请求。

    使用 NgFor 在模板中显示数据

    现在让我们在组件模板中显示新闻文章。打开 src/app/news.component.html 文件,更新如下:

    {{article.title}}

    <p>
      {{article.description}}
    </p>
    <a href="{{article.url}}">Read full article</a>
    

    资源:getting angularrest api

    【讨论】:

      猜你喜欢
      • 2023-02-08
      • 2018-08-12
      • 1970-01-01
      • 2021-02-17
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      相关资源
      最近更新 更多