自從我開始學習angular2以來,我正面臨着這個問題。 news.service例外:錯誤:未捕獲(承諾):TypeError:無法讀取null的屬性'0'任何建議嗎?
@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();
}
}
的問題是,當我嘗試使用任何服務像上面一個,在我的任何組件,如新聞分量的,我未定義在控制檯console.log(this.relatedNews [0])在ngOnInit,但爲console.log(this.relatedNews [0])在ngOnDestroy我有數組。此外,我可以在我的模板中使用相同的變量。
<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?
我試過了,發生同樣的事情。我沒有定義。我感到沮喪的是爲什麼它給了ngDestroy和模板中的正確結果,而不是ngOnInit –
@MohammedSabbah我不認爲你做了同樣的事情。它向你展示'ngOnDestroy'內的日誌的原因是因爲在'ngOnDestroy'中'this.relatedNews'變量有足夠的時間來定義。我在答案中寫下了一個類型,然後你可以像更新的那樣嘗試它。 – echonax
現在它工作得很好,非常感謝。那麼,現在對於有關新聞的操作我需要做同樣的事情?例如,如果我需要像這樣使用this.metaService.setTitle('News page'+ this.relatednews [0] .name);我是否需要像console.log一樣插入它? –