我从开始学习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;
}
新闻.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 中的 console.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);
});
是一个异步操作。您需要在回调 (subscribe
) 中使用 relatedNews
进行操作,如下所示:
this._newsService.getRelatedNews(id).subscribe(
(relatedNews) => {
this.relatedNews = relatedNews;
console.log(this.relatedNews[0]);
});
关于javascript - 异常 : Error: Uncaught (in promise): TypeError: Cannot read property '0' of null any suggestion please?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42243610/