自从我开始学习angular2以来,我就面临着这个问题。
新闻服务
@Injectable()
export class NewsServices {
private news: News[] = [];
constructor(private _http: Http) {}
getSingleNews(id: string): Observable <SingleNews[]> {
return this._http.get(`http://watania.info/getNewsById/${id}`)
.map((response: Response) => response.json());
}
export interface SpecialNews {
id: string;
title: string;
url_title: string;
image: string;
category: string;
summary: string;
date_to_publish: string;
}
news.component.ts
import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { NewsServices, SingleNews } from '../../services/news.services';
import { News } from './../../services/news.services';
import { Subscription } from 'rxjs/Rx';
import { VideosPage } from './../../services/videos.service';
@Component({
selector: 'wn-single-news',
templateUrl: './single-news.component.html',
styleUrls: ['./single-news.component.css']
})
export class SingleNewsComponent implements OnInit, OnDestroy {
sub: Subscription;
private selectednews: SingleNews[]= [];
private relatedNews: News[]= [];
constructor(private _newsService: NewsServices,
private route: ActivatedRoute) {}
ngOnInit (): void {
this.sub = this.route.params.subscribe(params => {
let id = params['id'];
this._newsService.getSingleNews(id).subscribe(
selectednews => this.selectednews = selectednews);
this._newsService.getRelatedNews(id).subscribe(
relatedNews => this.relatedNews = relatedNews);
});
console.log(this.relatedNews[0])
}
ngOnDestroy() {
console.log(this.relatedNews[0])
this.sub.unsubscribe();
}
}
问题是,当我尝试在任何组件(如新闻组件)中使用上述服务时,在ngOnInit的console.log(this.relatedNews [0])控制台中未定义控制台。 ngOnDestroy中的log(this.relatedNews [0])我得到了数组。此外,我可以在模板中使用相同的变量。
<h1 class="news-header"><span></span> {{selectednews[0]?.title}}</h1>
如上所示,在模板中使用变量时效果很好。但是每当我尝试在组件中使用它时
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of null
any suggestion please?
最佳答案
this._newsService.getRelatedNews(id).subscribe(
relatedNews => this.relatedNews = relatedNews);
});
是异步操作。您需要像这样在callback(
relatedNews
)中使用subscribe
进行操作:this._newsService.getRelatedNews(id).subscribe(
(relatedNews) => {
this.relatedNews = relatedNews;
console.log(this.relatedNews[0]);
});