Mohammed Sabbah
Mohammed Sabbah

Reputation: 883

EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of null any suggestion please?

I am facing this problem since I started to learn angular2. news.service

    @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();
    }
    }

The problem is that when I try to use any service like the above one, in any of my component like news component, I got undefined in the console for console.log(this.relatedNews[0]) in ngOnInit, but for console.log(this.relatedNews[0]) in ngOnDestroy I got the array. Moreover I can use the same variable in my template.

    <h1 class="news-header"><span></span> {{selectednews[0]?.title}}</h1>

It worked fine when use the variable in the template as shown above. but whenever I try to use it in the component I got

    EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of null
    any suggestion please?

Upvotes: 1

Views: 6035

Answers (2)

eko
eko

Reputation: 40647

this._newsService.getRelatedNews(id).subscribe(
        relatedNews => this.relatedNews = relatedNews);
    });

is an async operation. You need to do your operations with relatedNews inside the callback(subscribe) like this:

this._newsService.getRelatedNews(id).subscribe(
        (relatedNews) => {
          this.relatedNews = relatedNews;
          console.log(this.relatedNews[0]);
    });

Upvotes: 2

Uak
Uak

Reputation: 86

Put your console.log(this.relatedNews[0]) inside the callback of your service like this:

 this._newsService.getRelatedNews(id).subscribe(
    relatedNews => this.relatedNews = relatedNews);
    console.log(this.relatedNews[0])
});

normally your console.log will return your object

Upvotes: 0

Related Questions