在你的组件中注入 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 angular、rest api