Omkar Dixit
Omkar Dixit

Reputation: 766

Angular typescript object undefined at start leading to undefined error

How do i call the service to create the object first to avoid the undefined error ? The service this just return this.httpclient.get("serviceUrl") ts file

export class AboutmeComponent implements OnInit {

  personalInformation: Object;

  constructor(private portfolioService: PortfolioService) {
    this.getPersonalInformation();
  }

  ngOnInit() {
  }

  getPersonalInformation(){
    return this.portfolioService.getPersonalInformation().subscribe(data=>{
      console.log(data);
      this.personalInformation = data;
    });
  }
}

html file

<p>aboutme works!</p>
<mat-grid-list cols=4>
    <mat-grid-tile [colspan]=3>

    </mat-grid-tile>
    <mat-grid-tile [colspan]=1>
        <img [src]="personalInformation.profilePhotoUrl" alt="">
    </mat-grid-tile>
</mat-grid-list>

error

Cannot read property 'profilePhotoUrl' of undefined

Upvotes: 0

Views: 136

Answers (2)

user2216584
user2216584

Reputation: 5602

Although the solution provided by @indrajeet is fine. I would like to provide a solution using async pipe like this -

component.ts

export class AboutmeComponent implements OnInit {

  personalInformation$: Observable<any>;

  constructor(private portfolioService: PortfolioService) {
  }

  ngOnInit() {
    this.personalInformation$ = this.portfolioService.getPersonalInformation();
  }
}

html

<p>aboutme works!</p>
<mat-grid-list cols=4>
    <mat-grid-tile [colspan]=3>

    </mat-grid-tile>
    <mat-grid-tile [colspan]=1>
        <ng-container *ngIf="(personalInformation$ | async) as personalInformation">
            <img [src]="personalInformation.profilePhotoUrl" alt="">
       </ng-container>
    </mat-grid-tile>
</mat-grid-list>

Having async pipe in template avoids subscribing the observable in the TS file. async takes care of unwrapping the value from the observable. It also ensures to unsubscribe the observable [behind the scene] once the component destroys.

Upvotes: 2

indrajeet
indrajeet

Reputation: 897

component.ts

export class AboutmeComponent implements OnInit {

  personalInformation: Object;

  constructor(private portfolioService: PortfolioService) {
  }

  ngOnInit() {
    this.portfolioService.getPersonalInformation().subscribe(data=>{
      console.log(data);
      this.personalInformation = data;
    });
  }
}

html

<p>aboutme works!</p>
<mat-grid-list cols=4>
    <mat-grid-tile [colspan]=3>

    </mat-grid-tile>
    <mat-grid-tile [colspan]=1>
        <img [src]="personalInformation?.profilePhotoUrl" alt="">
    </mat-grid-tile>
</mat-grid-list>

Upvotes: 2

Related Questions