0

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
1
  • Just use *ngIf or default to an object with default values such as placeholder image src/alt. Also move those types of calls/inits to ngOnInit. Commented Jul 2, 2019 at 23:19

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.