我试图从其他API获取一些数据,然后使用angular 4进行ngFor。当我尝试记录时,我的组件返回一个未定义的数据:
服务:
getLatestFeed() {
let promise = new Promise((resolve, reject) => {
firebase.auth().currentUser.getIdToken(true).then((idToken) => {
var headers = new HttpHeaders()
.set('user_token', idToken);
var params = new HttpParams()
.set('page', '0')
.set('hits', '6')
.set('feed', 'latest');
this.http.get('https://dev-api.byrd.news/v1/stories', { params, headers })
.toPromise()
.then(data => {
return resolve(data);
})
}, error => {
reject(error);
})
})
return promise;
}
}
组件:
export class DiscoverComponent implements OnInit {
stories: any;
constructor(private storiesService: StoriesService, private http: HttpClient) {
this.storiesService.stories = this.stories;
}
ngOnInit(){
this.stories = this.storiesService.getLatestFeed();
console.log(this.stories);
}
HTML:
<h1>DiscoverComponent</h1>
<div *ngFor="let story of stories">
{{story.storyHeadline}}
</div>
我正在了解Observables和Promises之间的差异,并且我有点坚持这个。 有任何想法吗? 谢谢!