Issue: Encounter of an unexpected error: Unhandled Promise Rejection Error: It seems that there is a TypeError occurring where the property '0' of a null object cannot be read

Ever since I started learning angular2, I have been experiencing this issue with my 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;
    }

In the news.component.ts file:

    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 challenge arises when trying to utilize a service like the one above in any component, such as the news component. The console outputs undefined for console.log(this.relatedNews[0]) in ngOnInit, but it displays the array for console.log(this.relatedNews[0]) in ngOnDestroy. However, the same variable can be used in the template.

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

While it works fine when used in the template as shown above, attempting to use it in the component results in:

    EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of null
    Is there any suggestion to overcome this issue?

Answer №1

Upon calling the _newsService.getRelatedNews(id) method, it returns an Observable which requires asynchronous handling. It is crucial to perform any operations with the data received in the subscribe callback function as shown below:

Within the subscribe block, make sure to access and manipulate the relatedNews object accordingly:

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

Answer №2

Insert the console.log(this.relatedNews[0]) within the callback function of your service as shown below:

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

By doing so, your console.log statement will display the first element of your object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS gender dropdown with a default value of "empty"

I am still new to learning about angular and I am facing an issue with a dropdown menu for gender. I want to add a "--Select--" option, but it ends up duplicating. Below is the code snippet: <td style="font-family: Brandon-Grotesque, Helvetica Neu ...

In the world of NodeJS, the 'Decimal' module functions just as effectively when written as 'decimal'

I recently installed and started using the package decimal.js in my NodeJS project. If you're interested, you can find more information on this package here. What I found interesting is that while all the examples recommend using Decimal, I also not ...

Functionality issue with Angular's custom form control (Mandatory)

Exploring custom form controls in Angular has been quite an adventure for me, especially when it comes to setting required fields within a mat-stepper. My current challenge involves creating a reusable address template where I've configured the requir ...

Firefox throwing an error with jQuery URL Get requests

Could someone help me understand why my JavaScript function is triggering the error function instead of the success function in Firefox on Ubuntu? $(document).ready(function() { console.log( "Begin" ); $.ajax({ type: "GET", dataType: "ht ...

What steps should I take to include a Follow - Unfollow Button on my Website?

I need to add a button on my website that allows users to either follow or unfollow a specific game. Here is the table for the follow buttons: Follow Button Table When a user clicks on the button related to the game ID, it should update the game_follow d ...

Adjusting iframe height dynamically across domains using Jquery

Can this task be accomplished using jQuery alone without using any bulky plugins? While I am aware of the numerous plugins and alternatives available, I am looking for the shortest, most robust, and cleanest solution (ideally utilizing jQuery). Feel free ...

The Angular 2+ page fails to load properly on Internet Explorer or SharePoint

I created an Angular 5 solution that functions well in both Chrome and Firefox within SharePoint 2013. However, I have run into issues when using IE11. The index.html file was inserted into the SharePoint page using a Content Editor web part. Even after di ...

Serve different files using Node.js socket.io webserver, not just index.html

I recently started delving into socket.io and decided to use this chat example as a reference. As I navigate to ip:8080/public/index.html, I realize the need to access other files, such as additional JS scripts that will be used on the client side in the ...

Express.io is encountering an issue where it is unable to read the property 'expires' of an undefined element

I am new to working with node.js and I am attempting to utilize express.io for saving cookies. Following a tutorial at https://github.com/techpines/express.io/tree/master/examples#sessions, I have encountered the following error: root@server1 [/nodeexamp ...

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

Tailwind CSS not applying styles to my Next.js project on Ubuntu operating system

I'm experiencing a strange issue where Tailwind CSS is not applying any styles to my project on Ubuntu 20.04. Interestingly, the project works perfectly fine on Windows but for some reason, it's not styling at all on Ubuntu. https://i.sstatic.n ...

Validating dynamic textboxes in Angular with custom rules

Creating dynamic textboxes with *ngFor in Angular <tr *ngFor="let computer in _Computers; let i = index;"> <td>{{computer.Name}}</td><td>{{computer.Optional}}</td> <td> <input matInput [formControl] = " ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

Assigning arbitrary hidden form data from dropdown selection

Would like to assign Layers Value as one of the following: GFS Meteogram 3day std or WRF 20 Global Meteogram 3day Std depending on the option selected from the dropdown menu <div><select id="myselect" class="productViewerParameter" name=" ...

Setting up tslint to verify for unused variables in Angular2

Have you figured out how to set up tslint for checking unused variables and imports in Angular 2? I've added these two lines in my tslint file: "no-unused-expression": true, "no-unused-variable": true, However, it doesn't seem to be working. An ...

Utilizing Angular directives to trigger functions within nested child directives

Seeking guidance on implementing a hierarchical structure in Angular, where a directive (<partition>) can trigger a method on a child directive's controller (<property-value>). Sample example provided: https://jsfiddle.net/95kjjxkh/1/ ...

Ways to ensure CSS affects icon inside main element?

Struggling to match the background color of Material-UI icons with the rest of the list items on hover. The CSS is not applying to both the icon and text despite styling the overall class (className= "dd-content-item"). Any assistance would be greatly appr ...

The input texts are intertwined with one another through an autocomplete function

My latest project involves two input fields, one for ID and the other for Name. When I enter an ID in the first input field and then move to the second (either by pressing tab or clicking), the second input field automatically populates with the correspond ...

Eliminate the alert message that appears when dynamically rendering a React styled component

When checking the browser console, I noticed a warning that reads as follows: react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically. You may see this warning because you've called sty ...

The flow union type operates smoothly without any errors occurring

In the code snippet below, I have defined a type 'Something' which can have three possible values: 'A', 'B', or 'C'. The function 'f' takes an object of type Something as input and returns a string based on ...