The Angular 2 view appears on the screen before the data finishes loading in the ngOnInit

Utilizing the github API in my angular 2 application, I encounter an issue where the view renders before ngOnInit has finished loading data. This leads to a

Cannot read property of undefined
error. The relevant portion of my code is as follows:

ngOnInit() {
    Observable.forkJoin(
        this._githubService.getUser('kaxi1993'),
        this._githubService.getFollowers('kaxi1993')
    )
    .subscribe(res => {
        this.user = res[0];
        this.followers = res[1];
    },
    null,
    () => {
        this.isLoading = false;
    });
}

If I structure my HTML like this:

 <div *ngIf="user && user.avatar_url">
   <img class="media-object avatar" [src]="user.avatar_url" alt="...">
 </div>

everything works smoothly. However, if I exclude the *ngIf directive as shown below:

<img class="media-object avatar" [src]="user.avatar_url" alt="...">

I encounter the error

Cannot read property 'avatar_url' of undefined
. It's worth noting that while getFollowers behaves correctly, rearranging the order of getUsers and getFollowers within the forkJoin method results in the need for *ngIf on getFollowers. Is there a solution to this without adding extra *ngIf directives? Any assistance would be greatly appreciated. Thank you.

Answer №1

To prevent errors, you can make use of the safe-navigation (Elvis) operator like this:

<div *ngIf="user?.profile_picture">
   <img class="media-object profile-pic" [src]="user.profile_picture" alt="...">
 </div>

Alternatively, you can also do it this way:

<img class="media-object profile-pic" [src]="user?.profile_picture" alt="...">

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

Toggle the font weight in a text area by clicking a button

I need help with creating a button that will change the font-weight to bold when clicked and then revert back to normal when un-clicked. However, I only want the specific part of the text area where the user clicks the button to be bolded, not the entire t ...

What steps can be taken to fix the error message "Type circularly references itself"?

Here's an example of an issue with a predictable outcome: const actionTypes = { name: { set: "name/set", }, } as const; type ActionTypes = { [key: string]: (string | ActionTypes) }; //record value is string or ActionTypes // " ...

Enhance the efficiency of React code by optimizing the loading of data from multiple sources concurrently instead of one after another

In my project, there are 2 tabs displaying visualizations generated from separate data sources. Each tab requires multiple queries to be executed in the background to fetch the data, resulting in a delay when loading each tab individually. The current impl ...

Angular - Dealing with the value of zero in the @if template syntax

Having a dilemma with the Angular template flow syntax using @if. There is a value within an RxJs Observable, which is handled with the async pipe and assigned to a variable. @if (currentPageNumber$ | async; as currentPageNumber) { // currentPageNumber is ...

After refreshing the page, the initials vanish

One issue I'm facing is with a useEffect in my code. I am retrieving the name and email from my database and displaying the initials in an avatar in the header. However, after refreshing the page, the initials disappear. The commented code contains th ...

Sending JSON data from the primary window to the secondary window in Electron - A step-by-step guide

I am currently working with a set of 3 files. index.html: ... <a href="#" onclick="fetch(function(data) {console.log(data); subWindow(data)})">subWindow</a> ... The fetch() function retrieves a callback in JSON format. subWindows.js: let m ...

Angular allows for updating all preexisting values in an array by pushing elements into the array within a loop

I found an interesting problem while working on my code. I am trying to push the dates of the week into an array. Upon reviewing the code, everything seems fine until the // good value line where the array has the correct value. However, each time the co ...

Incorporate a visual element into an Angular Library Component Template using an image asset

Currently, I am working with Angular 10 and aiming to develop a component library that includes images and stylesheets. My main goal is to be able to access these images from the component templates defined in the HTML template. Although I have limited ex ...

What is the best approach to create a JavaScript search filter function spanning two pages?

Page1.html has a form with a drop-down menu containing options Color and Shape. There is also a submit button. Assuming Page2.html displays various shapes like Blue Square, Red Square, Blue Circle, Red Circle, is it feasible to create a JavaScript file th ...

Changing the value within a nested object dynamically in Angular 6 during execution

Currently working with angular 6 and have a method like this: public Save(): void { this.data.station.parkingSlot.forEach(p => { if(p.isAvailable){ p.isAvailable = false; this._carService.addCar(this.data); return true; ...

There was an issue trying to access the 'img' property of an undefined value in JSON data

I have successfully generated a JSON file containing data. Through the use of a provider in Ionic 3, I have managed to fetch the data. Below is the content of the JSON file [ { "teachers": { "img":"assets/home/img.png" } ...

"Techniques for extracting both the previous and current selections from a dropdown menu in Angular 2

How can I retrieve the previous value of a dropdown before selection using the OnChange event? <select class="form-control selectpicker selector" name="selectedQuestion1" [ngModel]="selectedQuestion1" (Onchange)="filterSecurityQuestions($event.t ...

The size of the card image and content area will remain constant based on the specified percentage

Looking for some guidance as I am still learning. I need the card below to have a fixed width of 38% for the image area and 62% for the content area, regardless of the size of the content (the height can increase if there is more text). In the image above ...

Exploring the enhanced capabilities of FeathersJS by integrating express-babelify-middleware

Attempting to integrate express-babelify-middleware with FeathersJS, an error message appears in the browser console: The error reads: ReferenceError: main_run is not defined This indicates that babelify may not be functioning correctly or I might be u ...

Logo remains in place when scrolling halfway down the page

I have a logo that I want to stay halfway up the home page when scrolling, as if fixed in place until it reaches the footer. body { background-color: #fff; margin: 0; } nav { position: sticky; top: 0; width: 300px; height: 80px; margin:4 ...

Perform a task upon clicking the JavaScript menu

Implementing dropdown menu items using a text link with JavaScript and CSS. You can view a demo here. I am looking to trigger an action when each menu item is clicked. Currently, they are not behaving as expected. HTML: <span class="inline-dropdown- ...

Working with JSON objects in AngularJS

I have a JSON dataset in the following structure. I need to extract information from the JSON and display it on an HTML table. [region: [name:"", code:""IntradayBalance:{ currency:,Time:,Balance: }.... ], acccountcurrencyBalance:[{ c ...

Tips for handling errors in ajax calls with alternative promises

While working on an application that offers weather data based on user location coordinates, I created the code provided below (also accessible in this codepen http://codepen.io/PiotrBerebecki/pen/QNVEbP). The user's location information will be retr ...

Transfer a csv file from a static webpage to an S3 bucket

Looking to create a webpage for uploading csv files to an S3 bucket? I recently followed a tutorial on the AWS website that might be helpful. Check it out here. I made some modifications to accept filename parameters in my method, and everything seems to ...

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...